Bodgers ‚Äď Prizes and Plans

It was great to see everybody back after the break.

I had a big box of goodies from the recent Raspberry Pi Pioneers competition. We got more swag for both teams that entered including some very nice badges and three really interesting books.

Our Zombie Trolls also got their prize for failing really well ūüėä. This included a Raspberry Pi, a 5‚ÄĚ HDMI Monitor, some basic electronic components, t-shirts and an Astro Pi Sense Hat (Hat stands for ‚ÄėHardware Attached on Top‚Äô).

The Sense HAT add-on board was specially created for the Astro Pi competition which gives kids the chance to get their code running on one of two Raspberry Pi devices that are on the International Space Station.Astro_Pi_Ed_and_Izzy_on_the_ISS

The board gives Astro Pi the ability to ‚Äėsense‚Äô and make many kinds of measurements, from temperature to movement, and to output information using a special display – the 8×8 LED matrix. We had great fun playing around with the Sense Hat and it‚Äôs definitely something we will get great use out of and maybe we could enter the Astro Pi competition and have our code running on the ISS.

We also took a look at controlling an Arduino from Unity 3D which is something that could be used for 4D/Immersive Technology type game.

See you all next week.

Declan, Dave and Alaidh

 

Creators – Unity Standard Assets

This week, in a fun and pretty free-form session, we looked at the Unity standard assets packs to get an appreciations of the wealth of valuable content they contain. 
We looked first at the Characters asset pack and tried the first-person, third-person and car controllers. 

We also used the Prototyping pack to place some basic house shapes and other basic level layout in our scene. 

Finally we played around with some of the effects in the Particles pack to see what was available there. 

Next week we will continue with another a session in a similar vein and explore the Environment assets pack and the creation of terrains to model exterior spaces. 

All ninjas are encouraged this week to play around with the standard assets, time permitting, and we may look next week at anything you’ve managed to create. 

Creators – Random Pin Placement

This week we worked on random pin placement for our game. We updated the existing PinManager component to randomly (as opposed to regularly) place a number of pins into the scene.

Arrays

An array is a way for a variable to hold more than one value. It’s a a very useful concept in programming; complex programs would be practically impossible without them. In C# arrays are declared as follows:

     int[] nums = new int[4];
     bool[,] grid = new bool[rows, cols];

The first line creates a one-dimensional array called nums which has four entries: nums[0], nums[1], nums[2] and nums[3].

The second line creates a two-dimensional array called grid. Note the size in this case depends on the values of the variables rows and cols. The first entry is grid[0,0] and the last is grid[rows Р1, cols Р1]. The total number of locations in this array is rows * cols.

Continue reading

Creators – Getting User Input

This week we worked on getting input from the user and making the game react to it.

InputManager

Unity has a build in system for handling user input. The InputManager can be found under the Edit|Project Settings|Input menu:

Screen Shot 2016-10-17 at 21.21.01.png

The Unity input system is based on¬†the concept of “axes”.¬†The game request if there is input on a specific axis, giving the axis name. What that means in terms of button presses, mouse or controller input depends on the settings in the¬†InputManager. Axes have a value that ranges from -1.0f (full negative, if negative values are allowed) through 0.0f (no input) to 1.0f (full positive).

inputaxes

Pre-defined Input Axes

While the game programmer can define as many input axes themselves as they like, Unity come with many common ones built-in. The first two¬†shown above, called “Horizontal” and “Vertical” are commonly used for movement. The third “Fire1” is usually used for shooting.

We redefined “Fire1” from it’s default key (Left Ctrl) to bind it to the space key instead.

screen-shot-2016-10-17-at-21-36-26

Updating the Code to Detect “Fire1”

We originally had a force applied to our ball in the “PushSphere” script as soon as the game started. We modified the code so that in the Start() method all we did was to retrieve and store the Rigidbody component. In the Update() method (called every time the game draws) we ask if there’s been any input on “Fire1” and only if there has, do we apply a force to the ball:

 using UnityEngine;
 using System.Collections;
 
 public class PushSphere : MonoBehaviour 
 {
   public float PushStrength = 1.0f;
   private Rigidbody rb;
 
   // Use this for initialization
   void Start ()
   {
     rb = GetComponent<Rigidbody> ();
   }
   
   // Update is called once per frame
   void Update () 
   {
     float fire = Input.GetAxis ("Fire1"); 
 
     if (fire > 0.0f)
     {
       rb.AddForce (Vector3.back * PushStrength);
     }
   }
 }

Before proceeding, we ran our game and tested to ensure it  was working correctly.

Moving Our Aimer

The aimer was rotated using input from the horizontal axis. We added a script called AimerController to our Aimer game object. A public property called RotateSpeed gives us a way to tune the speed our our aimer. We don’t need anything in the Start() method, and it’s been removed here for clarity. The Update() method looks for input on the “Horizontal” axis (which maps to the left and right keys) and applies a rotation to the Aimer’s transform using the following logic:

amount to rotate = speed of rotation * user input * time

User input here will either be -1.0f, 0.0f or 0.0f. This equates to rotate in a negative direction¬†(anti-clockwise), don’t rotate or rotate in a positive direction¬†(clockwise).

 using UnityEngine;
 using System.Collections;
 
 public class AimerController : MonoBehaviour {
 
   public float RotateSpeed = 1.0f;
    
   // Update is called once per frame 
   void Update () {
     float horiz = Input.GetAxis("Horizontal");
 
     transform.RotateAround (transform.position, Vector3.up, 
                             RotateSpeed * horiz * Time.deltaTime);
   }
 }

Note that we’re rotating about the vertical axis and the rotation is centred around the aimer’s position.

Linking the Aimer and the Sphere’s Direction of Fire

To link the aimer’s¬†with the sphere’s direction of fire, we needed to provide the sphere with a new public property which could store a reference to the Aimer’s game object:

public GameObject Aimer;

We then simply had to update the AddForce call, in the Update() method, to take the aimer’s direction into account:

 rb.AddForce (Aimer.transform.forward * -1.0f * PushStrength);

Note that we had to also multiply by -1.0f as the ball was initially going opposite to the direction we wanted.

Prefabs

Prefabs are objects, or collections of objects that we want to re-use multiple times. To create a prefab, all we need to do is to drag an object from the Hierarchy to a project folder. We made a prefab of our pin by doing this. Note that prefabs show up blue in the hierarchy to mark them out. When the prefab is changed, all copies of it in the hierarchy are updated as well.

Automatic Creation of Game Objects at Run-Time

Once we created our pin prefab, we worked on adding pins automatically into the game a run-time.

We added a new empty game object and named it PinManager, we then added a component to it of the same name. This script was given a public property, of type GameObject, to store a reference to the prefab. In the Start() method, we use two loops to place nine pins automatically into the scene, using the Instantiate() method:

 using UnityEngine;
 using System.Collections;
 
 public class PinManager : MonoBehaviour 
 {
   public GameObject PinPrefab;
 
   // Use this for initialization
   void Start () 
   {
     for (int x = -1; x <= 1; x++)
     {
       for (int z = -2; z <= 0; z++)
       {
         Vector3 pos = new Vector3(x * 2, 0.5f, z * 2);
 
         Instantiate (PinPrefab, pos, Quaternion.identity);
       }
     }
   }
 }

Note that there are several versions of the Instantiate() method. The version we’re using allows us to specify the position and rotation of the newly created object. A Quaternion is variable type that can store a rotation. Quaternion.identity simply means “no rotation”.

Testing

Project File

The latest project files can be downloaded from here.

Creators – Starting Our First Game

This week we started our first game in earnest. Let’s talk about the design and the steps we took to begin implementing it.

PinBowling.jpg

Game Design

The game involves a simple play area with pins. The players tries to knock down the pins by controlling the direction and force at which the ball is projected. The number of pins knocked constitutes the score. The game shares element of classic games such as pinball, bowling and skittles, to name a few.

Setting up the play area

To establish the play area, we used a plane (for the ground) and four cubes stretched to size to provide the walls:

gameboard

Because we don’t want gaps in our walls, we’ve been careful to be precise with the positions of everything.

Applying a Force to our Sphere

We added a sphere to our scene and made sure that it had a RigidBody body component. The RigidBody component makes it so that the physic engine takes care of the movement of the sphere.

To test adding a force to the sphere we added a temporary script to the sphere and had it add a force to the RigidBody as soon as the game starts.

Immediately it was clear that the force was too weak, so we added a property to the script which allowed us to scale the force. In testing 1000 proved to be a good value. Here is the script:

 using UnityEngine;
 using System.Collections;
 
 public class PushSphere : MonoBehaviour 
 {
   public float PushStrength = 1.0f;
 
   // Use this for initialization
   void Start ()
   {
     Rigidbody rb;
     rb = GetComponent<Rigidbody> ();
     rb.AddForce (Vector3.back * PushStrength);
   }
   
   // Update is called once per frame
   void Update () 
   {
   }
 }

 

We also experimented with creating a physic material and assigning it to the sphere. Different levels of friction and bounciness give different behaviours.

Testing With a Single Pin

To test the sphere colliding with a pin we added a single cylinder¬†to the scene. Like the sphere, we made sure it had a RigidBody component attached to it. When the game started the ball shot forward and knocked the pin, as we’d hoped.

Aimer

To aim our sphere and control the strength of our shot, we created an aimer. The aimer is composed of an empty object containing two cylinders, one pointing forwards and one pointing crossways.

We didn’t¬†want the aimer cylinders interacting with anything so we made sure to remove the colliders¬†from the cylinders.

We also wanted the aimer to be partially transparent so we created a new material, setting the Rendering Mode to “Transparent”, choosing a colour from the Albedo colour picker and setting the Alpha value to a value less than 255.

Screen Shot 2016-10-10 at 22.39.21.png

Project

Updated project files for this week’s project can be found here. This requires Unity Version¬†5.4.1f1 or later.

Creators – Covering the Basics

PhysicsTest

We’ve been busy the last two weeks covering the basics of Unity. Among the topics we’ve touched on are:

  • Customising the Unity layout
  • Explaining what the main Unity windows (Scene, Game, Hierarchy, Project and Inspector) are each for
  • Talked about 3D space and vectors and talked about the difference between local and global axes (child objects)
  • Shown how to place objects in the scene and how to position, rotate and scale them
  • Shown how to “fly” around the scene view
  • Explained how the physics engine works (Physics clock monitoring and moving rigidbodies and tracking collisions and other interactions)
  • Built a simple physics-based scene which had a ball fall, hit a ramp and roll into a bunch of stacked block
  • Wrote a script to have the camera follow the ball as it moves

 

Additionally Mike kindly filled in and talked about the basics of object oriented programming, classes and class diagrams.¬†There is a post from last year that covers this well for those who’d like to read it.

Additionally, the basics of the C# language that we discussed are covered in both that post which we have already linked to above and another which can be found here. The topics we touched on were:

  • Curly braces as “containers” and the requirement that they occur in pairs.
  • How semicolons (;) mark the end of statements
  • Using directives¬†and¬†namespaces.
  • A basic class declaration
  • Properties, both public and private
  • Methods, both public and private
  • How Unity automatically calls certain methods at certain times, and some specific examples of this:
    • Start()¬†called when we start the game
    • Update() called every time the scene is drawn

 

The up-to-date project file can be found here. Please note it will require Unity 4.5.1 or later.

Unity – A Basic Inventory System

backpack-145841_1280

Image from Pixabay

One of our ninjas was looking for a basic inventory system that he could use, so we knocked up something very quickly.

It’s all based on the standard .NET Dictionary class, documented here.

Dictionary allows us to store keys and associated values. In our specific case, our key is a string (the name of the item) and the value is an int (the count of items of that type).

This is all implemented in a script called InventoryManger.cs which is attached to an empty game object, also called InventoryManagement, for convenience. The InventoryManager class provides the following public methods:

void AddItem(string name)

This takes an item name. It looks to see if there’s an item of this name already in the inventory. If there is, it increases the count by one. If not, it adds it with a count of one. This cannot fail, so it doesn’t return anything.

bool RemoveItem(string name)

This takes an item name. It looks to see if there’s an item of this name in the inventory and that its count is greater than zero;¬†it’s possible that it’s listed there, but the count is zero. If there is, it decreases the count by one and returns true. If not, it returns false. The true/false return value allows us to test, when calling this method, if it succeeded, if that’s important to us.

int GetCount(string name)

This takes an item name. It looks to see if there’s an item of this name in the inventory. If so, it returns its count. If not, it returns zero.

So that allows us to add, remove and track an arbitrary number of items with very little effort.

The sample project also has a few other scripts. The intention is that the player picks up objects by moving over them. Pickup objects are tagged “PickUp”. The HandlePickup.cs script is added to the FPSController to detect moving over a pickup. Pickups have a PickupDetails.cs script attached. This automatically tags them “PickUp” and contains the items name (to use in the inventory). The project also has a FruitStealer.cs which removes one banana from your inventory every time you pass through its gate. It’s just there to show the RemoveItem method in action.

Screen Shot 2016-05-15 at 13.33.13

The files for this project can be found here.

Other small things of¬†note about this project: the “bananas” and “apples” are animated, as is the UI-text containing the text “Fruit Stealer”. The material used for the Fruit Stealer is¬†transparent.

 

Finishing our Game Projects

110401-N-HC601-027

Image from US Navy via Wikipedia Commons

With two more regular dojo sessions to go before our final party and belt awarding ceremony, the finish line’s in sight and we’ve been concentrating on helping people¬†work on their projects.

Some projects are already looking good, and that’s fantastic. Others however¬†aren’t showing a lot of progress.

If you are struggling, please¬†remember¬†–¬†overly ambitious scopes are the things that ruin most game projects. Ask yourself: what are the basic¬†things that¬†will be the¬†most fun in my¬†game? Maybe it’s exploration. Maybe it’s shooting.¬†Whatever it is, get that working as soon as possible. Don’t do ten weapons, do one. Other features can be layered on over time as long as the fundamentals¬†are there. Try hard to have something working for the next session. We’re here to help.

In the next session we’ll talk about the specific belts we’re going to be awarding. We’ll explain how they’re earned and¬†we’ll try to get an idea of how many people are going for each category.

Basic Sample Projects

I briefly showed a number of sample projects that I’d been playing around with this week. These projects are intended to demonstrate¬†certain useful things that you might want to put in your own game.

The first sample project was a modified version of SprocketLeague. The modifications were relatively modest: each car was given its own camera which was set to render into half the screen. The original top-down camera was set to render into a small area at the top of the screen.

The project files are available here.

The second project, called BasicAI, was just an experiment with baking a NavMesh and having an AI character follow you about. For extra fun, the followers spawn every 1.5s and they’re labeled “HipsterISIS” thanks to a very funny gag one of our ninjas made when watching the game run.

The project files for this are here.

Doors Project

This project wasn’t working fully during our session. It¬†is now. The project¬†contains two scenes. Both implement a door but in different ways. The two scenes can be found in the _scenes folder.

The first implementation is a physics based door. There is a box called DoorFrameRight which has a RigidBody component but is constrained so that it can neither move nor rotate:

Screen Shot 2016-05-08 at 14.57.38

Immediately to the left of this is the Door itself. This is also a box with a RigidBody component. In addition, it has a HingeJoint component. This HingeJoint component links it to the DoorFrameRight box. The HingeHoint is just visible as a small orange arrow on  the left hand side of this picture:

Screen Shot 2016-05-08 at 14.56.18.png

The HingeJoint component is positioned exactly where the door and door frame meet and its axis is set to be vertical, as the door is to swing around the vertical. It also has a spring which will close the door again (more or less) once the thing pushing it open moves away:

Screen Shot 2016-05-08 at 14.56.33.png

A regular FPSController can’t push this door, as it has a kinematic RigidBody (no physics),¬†so note that we use the RigidBodyFPSController instead to represent the player in this scene.

The other door works in a very different manner. The door consists of a frame and a “hinge”. The hinge is just an empty GameObject which contains all the parts of the door that will be moving. It’s origin is at the left-hand edge of the door panel; this means that when we change the hinge’s Y rotation, the door will pivot about it’s left-hand side. The hinge’s origin is shown here:

Screen Shot 2016-05-08 at 15.40.36.png

I could have made the hinge rotate in code, but instead I decided to create animations to¬†do the same thing (change the hinge’s Y rotation).¬†To explain how animation¬†works in Unity is beyond the scope of this post, but I’ll give a very broad introduction to it in the next session.

The door has a box collider around it. When it detects that the player has entered the collider, it triggers one of the opening animations (the direction depending on which side of the door it determines the player to be). Once the player leaves the collider, it closes the door again.

Screen Shot 2016-05-08 at 15.59.07

The files for this project are here.

Random Maze Project

This project was started live in our last session on the suggestion of one of the ninjas; it generates a random maze using a very simple algorithm.

An empty GameObject called MazeGenerator is placed in the scene. In its Start method, it constructs a random maze which appears in the scene. An FPSController from Standard Assets allows us to navigate this maze and try to find our way out.

The MazeGenerator constructs a 2D¬†array of bool values to represent the¬†maze. All the values in this array are ‘false’ by default and we take this to mean ‘solid’. Taking a point in the centre of the array we mark it ‘true’ to indicate an empty space. We then randomly pick a direction from North, South, East or West and set a new position. We check if we’ve moved outside the bounds of the array yet, if not, we mark this as another empty space and continue until we are outside.

Once we have this maze generated, we know we have a path from the centre (the start) to the exit (the outside of the maze). We loop over all elements in our array and place a solid block (from a prefab) everywhere we find a ‘false’, unless we’re at the edge of the maze in which case we place a special prefab that detect the player and plays a sound. This is our ‘exit’. For a ‘true’ we do nothing. The picture below shows one such generated maze from above.

Screen Shot 2016-05-08 at 18.35.04.png

To make this more fun to play, we also added a script to the FPSController to drop “breadcrumbs” as we move. This shows where we’ve already been so that going around in circles shouldn’t be a problem.

The files for this project are available here.

Review and a Couple of Sample Projects

This week we did¬†a review of everything we’ve covered so far in Unity¬†this year. It was a really usefully exercise as we ramp up to doing our own projects. People talked about their project ideas and I even got so see a few things running. I was impressed with the ingenuity and inventiveness. As I explained,¬†over the coming¬†few weeks, I won’t be presenting much in the way of new material.¬†We will instead concentrate on getting our projects running and polishing them to the best of our ability.

I presented a couple of small sample projects intended¬†to inspire game project ideas. The first was a top-down, single-keyboard, two-player game where two cars complete to drive a ball into their opponent’s goal area. If this sounds familiar, then you’ve heard of Rocket League. This low-rent version I dubbed “Sprocket League”. It can be downloaded from here. It uses the car from Standard Assets, slightly modified to allow the input axes to be defined in the inspector so that each can be controller independently. The red car uses the arrow keys and the blue keys uses WSAD for movement. To make it into a full game some means of keeping score and timing the game would be needed.

Screen Shot 2016-04-18 at 22.58.09.png

I also posted a basic sliding tiles game based on 2048. It is intended to show that we can achieve a 2D game appearance, even while¬†using the 3D elements¬†we have been working with. Although the basic game mechanics are there, it would ideally need a lot of work to bring it up to a reasonable standard. The real game provides a lot more visual feedback to the user than this version. Again, it can be downloaded from here. For those that recall, my broken attempt at making the tiles animate can be enabled via the “Show Me¬†The Broken Movement” checkbox on the GameController object.

Screen Shot 2016-04-18 at 22.54.20.png

Best of luck working on your projects over the next two weeks and I’ll see you all when we return!

Shooting Mechanics In Unity

It was a thrill to have such significant games industry figures come to visit us on Saturday. The mentors, dads and dad-mentors were probably the most excited; Wolfenstein 3D, Doom and Quake were probably the most exhilarating games of our generation.

I was¬†unsatisfied with how much benefit people were getting from continuing with the Tanks tutorial and I decided that we’d looked at it enough. Partially because I know some people want to implement shooting for their own projects and partially because one of our guests had invented the entire first-person-shooter genre, I decided to do a project to demonstrate¬†different ways of¬†implementing shooting in a game.

Please excuse the tinny sound; I was using the computers built in microphone.

There are two main ways to handle shooting:¬†ray-casting and¬†physics-based projectiles. We’re going to do both so lets discuss them in turn.

Ray-casting

Ray-casting uses mathematics to determine if a target is in our cross-hairs and, if it is, registers a hit instantly. It’s a good technique to use¬†where the bullet is very fast moving and distances are relatively short. Regardless of action movie tropes, nobody is¬†dodging a fast-moving bullet in real-life!

In Unity the Physics class¬†contains several Raycast methods (documentation here). They all look along a line from a point and return ‘true’ if that line crosses through a Collider. The specific version we’re using can fill in a RaycastHit object¬†with information about what it hit, if it hit anything.

To determine if we hit anything we must:

  1. Find the position and forward direction of the FPS Camera.¬†This represents where we are and where we’re looking towards.
  2. Call Physics.Raycast with this information. If it didn’t cross any colliders, then we are finished.
  3. If it did hit something, then we check to see if that object is a target. We have tagged all target objects in the scene as “Target” so we can easily check this.
  4. If it is a target, we perform the effect we want. In this case, we push the target away from us with force applied to its RigidBody . In another case, we might want to actually destroy the GameObject instead.

Physics-based projectiles

A physics-based projectile is actually an object in the scene. It has a Collider so that it can detect collisions and a RigidBody so that it is affected by physics.

In many¬†cases of physics-based projectiles, the¬†Collider is simply a trigger and once an collision¬†is detected, an effect, such as reducing the target’s¬†health,¬†is applied to the target.

Our specific physics-based projectile weapon is a cannonball. In this specific case, we actually allow the cannonball to hit the target and the physics engine takes care of the effect (knocking the target away).

The general steps that we need for physics-based projectiles are:

  1. Find the position and forward direction of the FPS Camera.¬†This represents where we are and where we’re looking towards.
  2. Instantiate an instance of our projectile prefab. Position it so that it’s slightly in front of us and not intersecting with the FPS Controller’s own Collider.
  3. Give the projectile some forward velocity.
  4. Either:
    1. Have the projectile detect collisions and perform an appropriate effect on the target, or
    2. Simply allow the physics engine to take care of the impact.

The cannonball prefab has a small script attached to it. It detects collisions. Once the first collision is detected, a coroutine is launched. This coroutine waits for two seconds and then destroys the GameObject. This means that cannonballs have a limited life-span and don’t end up littered¬†all over our level.

Area-effect weapon

We have also implemented an area-effect weapon, namely a grenade. In many ways it is similar to the cannonball but we project it with a more modest velocity.

Once¬†created,¬†however, it’s behaviour¬†is very different. A coroutine is launched as soon as it is created. This coroutine waits for a few seconds to mimic a grenade fuse. It then “explodes”.

To explode, the grenade does the following:

  1. Plays an explosion sound on it’s own AudioSource.
  2. Instansiates a particle-effect prefab at the grenade’s location to display an visual¬†explosion effect.
  3. Disables the grenade’s¬†MeshRender component so that he body of the grenade can’t be seen any more.
  4. Uses Physics.OverlapSphere (documentation here) to find all Colliders within a given radius of the grenade
  5. Loops over these Colliders. If the collider is not attached to an active GameObject or if that GameObject is not tagged as a target, we ignore it.
  6. If it is an active target, we use¬†RigidBody.AddExplosionForce (documentation here) to apply an explosion force, emanating from the grenade’s position, to the target.

Two seconds after the “explosion” the grenade GameObject, now invisible, destroys itself to remove itself from the scene. This short delay gives time for scripts to¬†complete and sounds to¬†finish playing.

Please note that¬†although the grenade wasn’t working correctly on Saturday during our session, it’s fully functional now.

Gun selection

Gun selection is handled using the “[” and “]” keys.¬†In the past we have tended to use Input.GetAxis to detect user input. This is good for¬†where we wish to perform an action continuously as long as¬†a key is held down. It’s not so good where we wish to perform a since action in¬†response to a single keystroke. For that, using Input.GetKeyDown (documentation here) is better and that’s what we do.

The selected weapon is stored using an enum. An enum is a special variable type which can only take one of a number of pre-defined values. Since we have a limited list of weapons, three to be exact, this works well for us.

Putting it all together

Screen Shot 2016-04-12 at 21.17.02

Our level is a simple terrain. It’s been textured and had trees, grass and a wind zone added to it. There is a simple lake. A few target spheres have been positioned around the map and a box containing a number of small targets has been¬†created as a good place to test the grenade in particular.

A standard first person controller prefab has been added to the scene. Our own GunController script has been attached to it as a component. GunController handles all the aiming and firing of the weapons.

Sound effects for the project are all from www.freesound.org with thanks to the original creators. All other third party assets are from the Unity Standard Assets pack.

Downloading the project

The project can be downloaded from DropBox here. Please ensure you have updated to Unity 5.3.4 before opening this project. Be aware, it’s relatively large at 160MB+.