Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

29. June 2017


In this section of our Bowling with Game Engines series, we will be implementing our bowling game in Unity. The idea is straight forward, implement the same simple 3D game across a number of game engines.  The Unity game engine is a logical place to start, as it is perhaps the most popular game engine in use today.  We will go step by step through the process of creating our game, both in text as well as a video version available here.   I am not a regular Unity user, so please do keep in mind, a lot of what I am about to show may not be best practice!  All of the assets used in this tutorial are available for Patreons as part of the bowling game kit, along with project files and this document in PDF form.  Don’t worry, these aren’t needed to follow along.

Let’s jump in.  Fire up Unity and create a new project.  In this example I am using Unity 5.6.1, however any recent version should work.


First, let’s start by dragging all of our required assets into Unity.  Simply select all of the game assets you will be using (FBX models, textures, audio files) and drag and drop them from Explorer or Finder into the assets folder.  If you are using the Patreon assets, simply copy the contents of Raw Assets in the Unity project folder.

clip_image002[4]


Unity does an extremely good job of importing assets and you should require no additional steps.  We now have all of the assets we are going to need to create our game, let’s get started.




Creating the Title Screen


First, we are going to start by creating a simple title screen with some awful looping background music.  We will be using our default scene for the splash screen and later we will create another scene for our actual gameplay.  We start off by saving our untitled scene.  Simply select File->Save Scene As…

clip_image004[4]

I saved it as TitleScreen. You should now have a new item in your assets list:

clip_image006[4]


We now have a few setup tasks to take.  We are going to be showing our title image and this requires us to alter the Main Camera entity. In Hierarchy panel select Main Camera, then in Inspector we change Clear Flags to Don’t Clear.

clip_image008[4]

This causes our camera to no longer have perspective ( things aren’t drawn smaller the farther away they get from the camera ).  Generally an Orthographic camera is what you use when working in 2D in a 3D world. Setting Clear Flags to don’t clear simply causes the default skybox to not be drawn, we could have optionally defined a background clear colour if we preferred. 


Now in Hierarchy panel, click the Create button, select UI->Canvas.  Next, with the newly created Canvas selected, click Create again and this time select UI->Panel.  At this point we should have this hierarchy.

clip_image010[4]


Next we have to make a slight modification to our imported Titlescreen image.  Select the Tilescreen.png image file in the assets view, then in Inspector change Texture Type to Sprite (2D and UI).  Then scroll down in the Inspector and click the Apply button.

clip_image012[4] 


Next select Panel in the Hierarchy view, and drag our newly created Sprite over to the Source Image section in the Image (Script) section.

clip_image014[4]


If you press Play now, you should see your Title screen in the viewport.

clip_image016[4]


Now let’s add a looping music file to our title screen.  In the Hierarchy view, select the Canvas entity.  Then in inspector scroll down and click Add Component, then Audio->Audio Source.

clip_image018[4]


In the newly created Audio Source in Inspector, drag our imported audio file over to the audio clip section.  Down below, make sure Play on Awake is set and then tick the box next to Loop.

clip_image020[4]


Ok, we now have a title screen and a sound track playing!  Good work so far… now let’s add a simple script that changes scenes on click. Let’s create our script.  Right click in the Assets area, select Create-> C# Script.

clip_image022[4]


Name it PanelScript.cs.

clip_image024[4]


Double click the newly created script file and it will open in your editor of choice.  Now enter the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PanelScript : MonoBehaviour {

   // Use this for initialization
   void Start () {
      
   }
   
   // Update is called once per frame
   void Update () {
        if (Input.GetMouseButtonUp(0))
            SceneManager.LoadScene("GameScene");
    }
}


Here we are simply checking every single pass through the game loop if the Left (0th) mouse button (or touch) is clicked, and if it is, we load the scene named “GameScene”.


Hmm… guess we should make a scene called GameScene now shouldn’t we?  Once again right click the Assets panel, then select Create->Scene.

clip_image026[4]


Rename the newly created Scene to GameScene.

clip_image028[4]


We are now done with our title screen scene.  Make sure you save.  Before we open our newly created GameScene, we have one last step to perform.  In the File menu, select Build Settings…, then select Add Open Scenes.

clip_image030[4]


Now double click our newly created GameScene to open it up.  If prompted to save, do so.  Now it’s time to create our game!


Click here to continue to part two!

Programming , , ,

29. June 2017

Click here for Part One

Creating the Game Scene


Now it’s time to get to work on creating the game itself.  Start off by dragging BowlingLane into the scene.

clip_image002


Now move the lane so it’s at position (0,0,0) in the Inspector under the Transform component.

clip_image004


One thing I noticed is the Normal map is way too strong.  Select the Bowling Lane material (either in the Materials panel, or drill down to it).  Dial back the Normal Map strength from 1.0 to 0.2.

clip_image006


We are almost done with our bowling lane.  The final thing we need to do is add a Collision Shape to it, so the rest of the stuff in our game world will interact with it properly.  With the BowlingLane selected, click Add Component->Physics->Box Collider

clip_image008


The nice thing with Unity is, it will automatically shrink wrap the collider geometry to match your mesh, so you should have to do no additional work!

clip_image010


So, that’s it for the lane, now time to create the Bowling pins.  Simply drag the Bowling Pin into the scene:

clip_image012


Hmmmm… pretty dark. What’s going on here?  Well, right now we are getting our lighting from the Directional Light in our scene.

clip_image014


We don’t want to mess around with advanced lighting, so instead right click and get rid of it. Now lets set up Ambient lighting instead.  Select Window->Lighting->Settings

clip_image016


Change Environment Lighting->Light Source to Color, then select the Ambient Color as white:

clip_image018


Now our scene will have universal consistent lighting:

clip_image020


Now it’s time to add some physics to our pin.  Once again we have to make a collision object component, but we also need to create a RigidBody component.  Add a Box collider just like before.  Then add another Component and select Physics->Rigidbody

clip_image022

The default settings are about right, so there is nothing else we need to do here.


The final thing we need to do with our pin is apply a tag to it so we can locate it using code later. With the Pin selected, in the Inspector at the top drop down the Tag drop down and select Add Tag…

clip_image024


Click the + Icon, then in the resulting text box enter “Pin” then Save.

clip_image026


Now select the Pin again, and in the Tags list, select Pin which should now be an option.

clip_image028


Now we simply need to create 4 ( or 9… depending your bowling preferences ) clones of our pin. Select the BowlingPin in the scene graph, right click and select Duplicate.  This will create a copy with all of the settings and components defined. 

clip_image030


After duplicating, position the pin and repeat the process until you have enough pins.

clip_image032


Click here to continue to part three.

Programming , , ,

29. June 2017


Click here to go back to Part Two.


Next, we need to create a bowling ball.  Instead of importing a 3D mesh, we are going to create one.  Select Game Object->3D Object->Sphere.

clip_image002


Once created, rename it to BowlingBall.

clip_image004

While we are here, create a new Tag called Ball and assign it to our object.


Let’s create a material for our Bowling ball.  Right click assets panel, select Create->Material.  Rename the newly created material BowlingBall.  Pick the color of your bowling ball with the box to the right of Albedo.  For shine add a small amount of Metallic as well.

clip_image006

Now simply drag the newly created material over to our Bowling Ball in the scene.


We also need to attach physics to our bowling ball.  This time it’s using a Sphere Collider.  This is also a rigid body, but this time we increase the mass to 3.

clip_image008


We are going to be putting all of the logic in our bowling ball.  One thing we are going to need to do is play audio when our ball hit’s a pin. We will add this logic later, but the audio source needs to be somewhere, so why not the bowling ball. We actually covered this process earlier when we added audio to our title screen.  Simply add an Audio Source component to the ball then attach the Hit.wav file, like so:

clip_image010

Tick off the Play on Awake checkbox.


Now its time to add some scripting to our game to control input and to deal with physics collisions when they happen. Right click the Assets panel and create a new script like we did earlier. Rename it BowlingBall.cs and drag it onto our BowlingBall object.  Now double click our script and enter the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BowlingBall : MonoBehaviour
{
    public float force;
    // Use this for initialization
    private List<Vector3> pinPositions;
    private List<Quaternion> pinRotations;
    private Vector3 ballPosition;
    void Start()
    {
        var pins = GameObject.FindGameObjectsWithTag("Pin");
        pinPositions = new List<Vector3>();
        pinRotations = new List<Quaternion>();
        foreach (var pin in pins)
        {
            pinPositions.Add(pin.transform.position);
            pinRotations.Add(pin.transform.rotation);
        }

        ballPosition = GameObject.FindGameObjectWithTag("Ball").transform.position;
    }


    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.Space))
            GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, force));
        if (Input.GetKeyUp(KeyCode.LeftArrow))
            GetComponent<Rigidbody>().AddForce(new Vector3(1, 0, 0), ForceMode.Impulse);
        if (Input.GetKeyUp(KeyCode.RightArrow))
            GetComponent<Rigidbody>().AddForce(new Vector3(-1, 0, 0), ForceMode.Impulse);
        if (Input.GetKeyUp(KeyCode.R))
        {
            var pins = GameObject.FindGameObjectsWithTag("Pin");

            for (int i = 0; i < pins.Length; i++)
            {
                //collision.gameObject.transform.parent.gameObject.tag
                var pinPhysics = pins[i].GetComponent<Rigidbody>();
                pinPhysics.velocity = Vector3.zero;
                pinPhysics.position = pinPositions[i];
                pinPhysics.rotation = pinRotations[i];
                pinPhysics.velocity = Vector3.zero;
                pinPhysics.angularVelocity = Vector3.zero;

                var ball = GameObject.FindGameObjectWithTag("Ball");
                ball.transform.position = ballPosition;
                ball.GetComponent<Rigidbody>().velocity = Vector3.zero;
                ball.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
            }
        }
        if (Input.GetKeyUp(KeyCode.B))
        {
            var ball = GameObject.FindGameObjectWithTag("Ball");
            ball.GetComponent<Rigidbody>().velocity = Vector3.zero;
            ball.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
            ball.transform.position = ballPosition;
        }
        if (Input.GetKeyUp(KeyCode.Escape))
        {
            Application.Quit();
        }
    }
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Pin")
            GetComponent<AudioSource>().Play();
    }}

We publicly expose the Force value, which is the amount of energy to apply along the Z axis when we throw the ball.  Since it is public, it’s settable in the editor as a property in the script component.

clip_image012


And done!


The Video

Programming , , ,

12. January 2017

 

Today we are going to take a quick look at the Tilengine 2D game engine.  Tilengine in their own words is:

Tilengine is a free, cross-platform 2D graphics engine for creating classic/retro games with tilemaps, sprites and palettes. Its unique scanline-based rendering algorithm makes raster effects a core feature, a technique used by many games running on real 2D graphics chips.Untitled 3

Tilengine is open source (sorry, the core isn't open ), available on Github however I never could locate what license it’s released under.

EDIT—Since posted, there has been a bit of conversation about the licensing since this was posted, read here.

  It’s a C library, but contains bindings for Python, C# and Java.  I’m actually going to use the C# bindings for the example in this review as it’s the least documented of the available bindings.  There is a single page class reference available here and a small manual available here.  The engine is geared towards creating retro sprite style games and handles graphics, animations, palettes, input and window management, but has no sound or physics engine built in.  It is also designed to be used as a backend solution to an existing front end renderer.  There are several C based examples available here, and this represents the primary way you will get up to speed.  The graphics system is designed to emulate classic sprite systems like Sega’s SuperScaler arcade board but with Super Nintendo’s Mode 7 style graphics effects available.  Tilengine is layered over SDL and is cross platform, capable of running on most desktop operating systems, as well as Raspberry Pi devices.

Tilengine is composed like so:

image

 

Tilengine has direct support for tiled map files created using the Tiled map editor.  If you want to learn more about Tiled, I have done a complete tutorial series available here.

 

As a pretty straight forward game engine, let’s jump right in with the example created using the C# bindings:

using Tilengine;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var engine = Tilengine.Engine.Init(320,240,1,16,16);
            var window = Tilengine.Window.Create("",Tilengine.WindowFlags.Vsync);
            
            // This is the clear color drawn each frame.  Think of it as the sky color
            engine.BackgroundColor = new Color(0,128,238);

            // Load tsx and tmx file.  These are created in the Tiled level editor
            // tsx is a collection of tiles, tmx is a map painted using those tiles
            var tileset = Tileset.FromFile("SOTB_bg.tsx");
            var tilemap = Tilemap.FromFile("SOTB_bg.tmx","Layer 1");
            
            // create a new layer using our just loaded tiles.  Games can have multiple layers
            var layer = new Layer();
            layer.Setup(tileset,tilemap);
            layer.SetPosition(0,0);

            
            // Now we are loading an animated sprite riped from the 90s classic Shadow of the Beast
            // Spriteset is simply the image collection composing our game Spriteset
            // SequencePack is simple text format describing the available animations, their frames, speed etc
            // While Sequence is a named entry in the SequencePack text file
            Spriteset ss = Spriteset.FromFile("SOTB");
            SequencePack sp = SequencePack.FromFile("SOTB.sqx");
            Sequence walk = sp.Find("walk");

            // Now finally create a sprite using our spritesheet
            Sprite sprite = new Sprite();
            sprite.Setup(ss,TileFlags.None);

            int spriteX = 15;
            sprite.SetPosition(15,215);
            
            // Now play the animation sequence named "walk".  We also pass the final 0 in to tell it how many times the animation
            // should loop.  Zero equals forever
            Animation anim = new Animation();
            anim.SetSpriteAnimation(0,walk,0);
            
            
            int frame = 0;

            // This is your game loop
            while(window.Process()){
                // Draw the current frame of graphics (sprites, layers, etc)
                window.DrawFrame(frame++);

                // Now check if left or right arrow/gamepad are pressed, in which case move in that direction
                // IF moving left, flip the sprite over on the X axis
                if(window.GetInput(Input.Right)){
                    spriteX ++;
                    sprite.Flags = TileFlags.None; 
                }
                if(window.GetInput(Input.Left)){
                    spriteX --;
                    sprite.Flags = TileFlags.FlipX; 

                }
                sprite.SetPosition(spriteX, 185);
                if(spriteX > engine.Width) spriteX = 0;
            }
            

            //Cleanup
            tilemap.Delete();
            tileset.Delete();
            window.Delete();
            engine.Deinit();
        }
    }
}

 

The comments pretty much describe everything that is going on there.  For more details, be sure to check the video version of this tutorial available here [coming soon].  This example loads a sprite and animation from the game Shadow of the Beast, an Amiga platformer classic.  The SequencePack file format is extremely simple XML file, here is the example used:

<?xml version="1.0" encoding="UTF-8"?>

<sequences>
  <sequence name="walk" delay="6" loop="0">
    1,2,3,4,5,6
  </sequence>
</sequences>

 

The tsx and tmx files are generated using the Tiled level editor, another open source and free tool.  As you can see, it’s extremely simple to get up and going.  Run this code you will see:

SOTB

 

This is of course a primitive example, but does show the many parts of a game.  A game loop, sprite loading, animations, level loading, etc.  The major features of the engine, that I’m not covering here, are the various sprite effects it emulates.  You can see these effects demonstrated here or in the samples.

 

The Video

Programming , , ,

8. July 2016

 

Released just a few days ago on the App Store is Continuous, a complete C# and F# development environment that runs directly on your iPhone or iPad.  It contains a fairly full featured IDE with capable text editor, programming friendly on screen keyboard and more.  In addition to the editor it contains everything you need for development, a port of the Roslyn compiler, VM as well as implementations of several key libraries such as Xamarins WinForms implementation.

From the App Store entry:

    • Continuous is always building and running your code so you can see changes as you type. Writing interactive apps in Continuous is a pleasure compared to the traditional code-build-run cycle. It frees you to make lots of small changes and see their effects immediately - no more waiting for builds or deployments and no more clicking around trying to get to the screen you're trying to code.
      Continuous looks and works in many of the same ways as traditional .NET IDEs so you'll feel right at home, but it also strives to advance the state of the art in IDEs with these features:
    • Full C# 6 and F# 4 compilers so you can use the latest tech
    • Automatic compiling and running so you can focus on the code and the results
    • Fancy text editor with tabs, semantic highlighting, inline error bubbles, and inline values that are updated as you type
    • Watch window enables you to view graphical objects in your app (UI and images), inspect live objects as your app runs, create instances of new objects, and call methods
    • Code completion with inline type info and documentation makes learning new APIs fun
    • Uses standard .NET file and project formats so you can share code with other IDEs
    • Includes Xamarin.Forms and UIKit to build apps and SpriteKit and SceneKit to build games
    • Split screen support so you can keep documentation by your side
    • Execution powered by a new IL interpreter

 

If you are interested in learning more I already did a hands-on video available here or embedded below.  After some more experience I may follow up with a full blown review.  If you are a C# developer and are interested on developing directly on your device, check out Continuous.  It’s a pretty amazing piece of software.

 

GameDev News , ,

Month List

Popular Comments