I dabbled with Unity’s animator a while back but ever posted about it. Having revisited the topic today I’ll cover both parts of the exercise in one post. Initially I had heard that the animator could be used to control the doors in my walking simulator but at that time never looked into it and instead relied on using the iTween plug-in. Having learnt what I have today I’ll rely on the Animator from now on, it uses almost no code and is far simpler to use. Especially for the basic movement of doors, windows etc. We setup a swinging lamp and an opening door, the lamp would swing forever on a loop but the door would be triggered by script to call upon its various states of animation.
I loaded up the old room scene we were given at the start of the year (as an introduction to the walking sim exercise) and created a lamp shape out of primitives. The issue with this is that all Unity primitives have their pivot point set to the centre, and this isn’t useful for a swinging lamp. There are two ways around this, you either model the object in another package and set the pivot point before import or parent all the Unity primitives to an empty game object and use that as a pivot.
Once you get into the Animator (Ctrl+6) it’s a familiar sight if you’ve used any other animation software. The keyframes are similar to those in After Effects. Unity runs at 60fps default so there is a little more space to fill every second but for the sake of swinging a lamp it wasn’t an issue. Move to one extreme and key, move to the other and key and then smooth the curves out in the curve sheet so the loop works better. Jump back into gameplay and the lamp will swing forever in the scene. I can think of very few scenarios where an object in a scene would have perpetual motion, however we’ll address this in the next exercise.
As I mentioned earlier, knowing about animation states would have been infinitely useful for my walking sim. The best way I can explain it is linking together small clips of animation using transitions. Here is a diagram that will make far more sense than me:
So during the exercise I created three animation states, door idle, door opening and door closing. The arrow flow in the diagram are your transitions, for example door idle is your default state of the door, closed in its frame with no animation. Idle can only realistically transition to door open, transitioning to door close would require the door to be open first. Oh I should also mention that the timings of the door will all be dependent on your key frames like any animation.
Once we have setup code, an object/button in the scene will allow us to move through these transitions with ease. Even if the door is only half open and we click to transition, Unity will automatically figure out how to smoothly close the door without jumping to the beginning of the door close animation. Absolutely genius stuff and would have saved me days of headaches back in November.
However I should note setting up the transitions is not the end of the story, if you play the scene the door will loop forever even if the code was in place. First we need to untick the Has Exit Time radio button and add a trigger condition to every transition, in this instance it was named toggle.
Within the inspector properties for each individual animation cycle the radio button for ‘Loop Time’ also had to be disabled.
Add this wonderfully simple bit of code to an object in the scene, replace the triggerName in the inspector with ‘Toggle’ and magically a working door happens with almost no scripting. We could have set the triggerName in stone but its nice to be able to re-use the script elsewhere.
This week took a different turn in Programming, beginning with a simple concept that would help us review correct syntax and then an exercise to keep us busy over the week involving an arena of bouncing balls (more on this later).
Our simple task was to create a small script that may be useful as a portfolio entry, it would rotate and show off 3D models. The suggestions given to us were:
Rotate around the Y axis each frame.
Use a variable for the rotation speed.
Change rotation direction when clicked.
Rotate in X axis if space is being held.
Scale up and down with arrow keys.
Bob up and down with a sine wave.
Along with these suggestions the only bit of base code provided was:
Thankfully this seems to be a common exercise as there are plenty of helpful hints and tips across the internet for setting up similar scenes. Here are a breakdown of my variables:
I know I’ve commented a lot of it in the script so I’ll try not to repeat myself too much. The float originalY will be used later to determine the starting Y position of the cube, this is needed for the MathF.Sin which will calculate our bobbing motion. The two rotate floats will be used to determine rotation speed and the floatStrength will determine the intensity of the bobbing.
On the scene starting our originalY float will determine its value by looking at where the object is on the Y axis. This will be used later to determine the home value of the bob, for lack of a better term.
Here is the meat of the script driving the scene. On the first line you can see the good old rotate script being used to spin the object in the Y axis, nothing new here.
The transform.position is our sine wave creating the bob. Within the vector3 x and z are set to get current position but Y takes the originalY value and adds a MathF.Sin over time * the float strength variable. The strength variable determines the height of the wave and therefore the top and bottom positions of the bob.
The final GetKey function spins the object on its X axis when space is pressed, mostly the same as the previous rotate code.
For the last little bit, when our mouse is clicked it changes our rotateY value to a minus value, making the object spin in the opposite direction. Tada! One model spinning bit of showcase code! The only thing I didn’t squeeze into this exercise was the scaling up and down with the arrow keys. I’ll have to return at a later date and figure this out.
It’s class deathmatch time, last man standing! We have been given an exercise to code an ability onto a basic sphere. These will all be dropped into an arena next class and we get to watch what carnage happens (I’m betting on Unity breaking personally). Everybody has to take the player tag for their sphere and we aren’t allowed to delete the floor, these are the only rules.
I’m not finished the exercise yet but I can bring you up to speed to where I currently am. Initially I didn’t know where to begin, all I knew was I wanted a clone mechanic on collision but first wanted to tackle the balls movement. A standard bounce with a physics material would slow down pretty fast and lay dormant in the arena, minimising the chance of further collisions. To solve this I setup float variables for x, y and z velocity but had the value set to a random range which would trigger on collision with any surface, theoretically keeping them alive forever and unpredictable.
The rest of this script adds force to collisions if that happens to be anything with the player tag. Currently I don’t know exactly what ForceMode is doing, as I pulled it straight off the Unity database and tested it. However its creating some interesting results, akin to the movements you’d expect from a deflating balloon. I may leave it in purely for comic value. The end of the script calls the CloningFunction twice which I’ll explain in a moment.
So the CloningFunction isn’t calling a simple prefab, since we have no control over the final scene in Unity everything needs to be contained within one script. To get around this I create a brand new primitive game object sphere, assign this as a child of the ball that created it and add a rigidbody, the whole script, a renderer material colour and a tag without need of the inspector. Therefore making the new child ball a duplicate of its parent.
This is my progress so far, I’ll come back later in the week to try and add a few more features.
As an added bit of fun I added a change of mass to objects being collided with, reducing their mass to 0.09, which when paired with the ForceMode.Impulse creates some rather hilarious physics practically shooting other balls out of the arena at high speed. This lives within the OnCollisionEnter function:
collision.rigidbody.mass = 0.08f;
The only other change that has been made is clone spawns of the original ball now don’t parent to the original. Turns out if the parent gets destroyed (if another player decides to get cheeky) it’ll destroy all the children too.
This week we finished off the individual games, finally making them something of a clone of the group games with the exception that we’d understood and done all the work as individuals. I hope now this prepares me for the exam, I have zero worries about the rest of the course but a code exam? Artist’s nightmare! I over-react, the whole thing is open book and with enough preparation I’m sure I can knock out another game similar to this within the allocated period.
Okay first task on the list, the guard needs to shoot. Took the code from Ant’s notes and the previous Trio game, bam done! The highlighted code was the edit made later on in the lesson to get the guard to shoot at the player once they’re in its cone of vision.
At this moment the code had no idea what on earth projectilePrefab was, so retroactively I imported the same laser graphic used previously (from the wonderful kenney.nl), tagged it with “Laser”, added the Projectiles script (as seen below),prefabbed the whole thing and plugged this into the public GameObject seen above in the inspector.
So now our baddie shoots constantly and we can be hit by bullets. This is pretty much the point where I stop wrapping my head around it all, now to introduce sight to the guards. I mentioned in a post during the trio game that I wasn’t sure if line of sight was going to be required in the exam, turns out it is. So somehow I’m going to have to wrap my head around this or risk failing, which absolutely isn’t an option.
Easier said than done. During the trio game Ant more or less coded this in on our request and this time around the code was provided to us, we just had to understand enough to be able to implement it onto the correct game assets. So while that I achieved, I honestly can’t talk you through it, nor do I want to delay this post until I have a better understanding. I’ll have to return and wrap that loose end up in future before the exam.
At least I can explain some of the setup new setup, improved on since the trio game.
Above are the variables declared in the ConeandLineofSight script, the two I want to focus on are the public MonoBehaviours, normal and chasing component. These create placeholders in the inspector in which to plug in other scripts, this will be used to change the guards behaviour when he sees the player and doesn’t. He’ll either patrol as normal with the waypoints script or stop and shoot at the player using the autofire script.
The use of these variables can be seen above further down the script, activating and deactivating these as needed.
For reference here is the cone and line of sight parts of the script.
Carrying on from last week, we were back to our solo games. Ant revisited the waypoint code for the guards for us to implement. Having covered this twice before I had my one lone scientist setup to patrol back and forth (to what would eventually be the locations of two computers) in a jiffy. I didn’t need to use an the more advanced waypoints script with the array for this simple first room however I’ll revisit that later in another level. I won’t post the whole guard script again as we have plenty of older posts covering this.
Originally the scientist sprite didn’t rotate, I had managed to code this into the player character using some code found online. I asked for some assistance from Ant to reverse enginner this to work for the scientist and it now works a treat.
We also needed a fail/game over condition added this week. The best place to start with this would be collision with the now mobile scientist/guard. Nobody is firing projectiles yet, or seeking the player so it seemed like the only reasonable fail condition for the first level. Using tags to identify the scientists an OnCollision2DEnter was setup within the player movement code to identify collisions.
Next on the agenda was exiting the level which took a few steps. I wanted a keycard to be collected before exit was allowed and hope to retain these cards to open up colour coded doors in future levels. This takes us right back to the beginning of the year when setting up the key/door in our first Unity project. On top of this I also added an inventory list to store the item, the same as my walking simulator.
The collision detection to exit the level with key in hand was also added to the player controller script. I won’t repost all of the inventory scripts as again they have been covered before in older posts.
Having gotten to the optional part of my checklist I attempted to make a particle system that identifies to the player a key has been picked up. I had spare time in class and decided to tinker.
I’m not super happy with it and need to tinker with it further to make it far more subtle, and also need to gain the knowledge of how to call upon it. Things to do, things to do! Be back next week for another update!
The programming exam looms upon us and in further preparation for the jam aspect of it, we’ve all been separated from our previous duo/trio teams and have been tasked with making the same kind of game completely solo. This is quite the task, but as long as I try to tackle it one function at a time I’m sure I can get through it.
For the first time we were asked to use/make our own assets for the game, which meant picking a theme too. Ant handed out post it notes and told us to list all the things we wanted to accomplish that lesson, a lovely method of breaking down tasks and one I used for years, especially in an IT office environment.
I decided to keep things as simple as possible and would have a robot trying to escape from the facility it was built in. Navigating levels, avoiding guards etc. I could add pickups in the form of keys, maybe even batteries.
For week one I decided the bare minimum to achieve was this:
Draw robot asset
Create assets required to assemble a first level (walls, floors etc)
Draw a guard/scientist
Code the movement for the robot
Introduce the game in a blog post
I’m not going to break them all down one by one, so here are all the assets created this week:
Yes, before anyone eagle eyed comments, the scientist was taken from my Xmas Game Jam attempt. No harm in re-using my own assets. I made a wall tile, a floor tile, the good player robot, baddie robot guards and for some reason a potted plant (the level was looking bare). I can likely salvage a few more assets from Xmas such as desks, computers etc which will help as set dressings.
From a quick week one assembly, here is my initial level. I aim to have the guard pacing between two computers and the baddie robots are dormant. Just a first easy level to establish mechanics. The movement is all in and working, I expanded on the basic movement with some code found on google, so now the sprite rotates to face direction.
Hopefully I can get ahead of the curve and maybe add the guard movement before next week, along with an exit to level two.
We have been asked to add a feature to one of the many games we’ve worked on that has been discovered through self tuition and the Unity documentation. This has never been my strongest area so I thought it would be best to keep things simple.
In my walking simulator I had a locked door on the bottom floor with an inaccessible room behind it, I had originally planned to make some combination of a mis-functioning door/jump scare. Working with this I thought I could add a key card reader, so a panel that would interact with a key, give an indication the key has been accepted with a change of light and then begin to open the door with a failure.
Using the Renderer in Unity was one of the recommendations in class for things to look at, and I’ll be needing use of it to complete this feature.
I started (in a new script) by declaring the variables I’d need:
public string keyItemName – Has seen use before and allows me to type in an item name which can be searched for in the inventory list.
public GameObject light – At some point I’d need to affect a game object I’ll be changing the material of, in this case I named it light.
public Material lightOff – To allow me to set the material for the off state.
public Material lightOn – To allow me to the material for the on state.
public GameObject door – Once the lights had been changed, I wanted the nearby door to open.
Renderer rend – Declaring we’d need to make use of the renderer and called it rend, also a private variable as nothing else will need to use it.
Here is how it looks in the inspector, after being attached to the object in the scene which would be used as a button to trigger the script. The item required has been input, which game object will be our light, on and off materials have been setup and input and the door declared.
Continued on in the script, we use existing script to access the inventory controller and look for the KeyItemName (declared above). If the item is found the script goes looking for the renderer component for the variable light, which will point to our physical game object (in the actual scene this is just a sphere).
We’re then asking the renderer to change the material for the object to what has been declared in lightOn variable. You can see above how the renderer for light looks in the inspector, we’re asking the script to change the entry in Element 0.
Finally using old iTween code, we tell the door to raise in the Y direction. Now all my other doors are raised by 3 units which grants a full open, I already mentioned I wanted the door to malfunction so only raised the door half height (1.5f) to make it inaccessible to the player. The script then destroys itself so the door can’t be raised further by the player continuing to press the button.
Here is how it looks when played:
Technically we didn’t need to declare the lightOff material as the light never returns to its original state. However I could modify the other doors in future to all have open/closed indicators and wanted to leave the variable in for this reason.
To start this lesson off we were shown some examples of how to calculate dot products of some vectors, using a different method to the one I had researched last week:
a · b = ax × bx + ay × by
Above were the examples (with answers now included) we were asked to work through during the lecture. After all the confusion I had researching these the week before, it all boils down to some multiplication between vectors. I don’t normally post any workings we do mid lecture but this time around I thought it would help me leaving them here for reference.
So if the end number is positive, it means there are less than 90º between two objects and if its negative there are more than 90º between the two.
So all of this is the background theory behind what we would implement in our games today. Guard line of sight/cone of vision. The code was supplied by Ant, as per usual and we jumped right in and pasted this into the existing guard script. It worked but the cone only ever pointed in one direction, and we felt it should change depending on the direction the guard was heading.
Ant assisted us in correcting this by using the direction of the guard waypoints to determine the facing direction.
Further adding features we wanted the guard to be able to shoot towards the player when they are within their cone of vision. Sounds easy enough but again, after much googling and frustration we ended up asking Ant who spent a great chunk of time adding this functionality. I believe we determine the direction of the projectile by taking the searchTarget position and substracting the transform.position.
I must admit we’ve reached a point in programming where it really is getting beyond me, the best I can do in these blogs is summarise what happened. Explaining in detail is becoming troublesome. The college is still unsure what will make it into the programming exam and what won’t, so I’m busy crossing all fingers and toes that this level of scripting isn’t required. I won’t deny that the end results are great, I’m having fun playing our own game and it’s only had three works of lesson time put into it.
I have begin to see a pattern with these research tasks and posts. I spend a week staring at wiki, struggle to take in and process the information I’m seeing, given context in class and everything makes more sense. So from now on I plan to keep these brief with the most basic of understanding.
A for loop appears to be a way to repeat a block of code a known amount of times. Similar to a while loop except it eventually has a condition where it terminates. Even if you as a coder aren’t sure of the amount of times the code will need to repeat to achieve the condition, it is still classed as a known amount of times and will be a for loop.
The general syntax seems to look like this:
Init – Declare and initialise the control variables involved in the loop
Condition – If the condition you set is true, the loop runs, if false then the loop stops executing.
Increment – Allows the updating of control variables
As for for each loops the main difference I can see is that a for each loop are used to iterate the same action in sequence for everything in a collection.
So rather than looking for a condition to be met, you’re just repeating an action on whatever you put into the loop. I’m hoping I’ve got this right, if not I will return next week and correct my description!
This may be purely copying from source online, I’ll explain up to what I can understand and leave the rest for a good class explanation.
So a vector has magnitude (how long it is) and a direction. We know this from previous classes. If you have two vectors, they can be multiplied together using a dot product. I don’t know to what end but I’m sure that will be explained. The resulting number returns something called a scalar not a vector number.
To calculate we take the magnitude of the first vector, multiply it by the magnitude of the second vector and then multiply the result by cosine.
I’ll cut it there for this week and hope to make more sense of it all soon. Online the examples continue into 3D and it all gets very complex, very quick.
A new week and a new mechanic to incorporate in our trio game, in preparation for the upcoming exam. We’d be looking at projectiles and how to incorporate/instantiate them into games.
The example given to us had three different ways in which it could be used:
An automatically fired projectile.
A projectile that fires on a key press.
A series of projectiles on a key press fired at angles around the player.
All very cool, however this needed adapting for use within our game ‘A Bouquet for My Lady’ so that the guards would fire a projectile at the player if they came too close. Feeling optimistic today I volunteered to be the one to take a stab at making this work.
Before I began playing with the code I knew I didn’t know how to give the guards a line of sight, for now I thought an easy way to get around this would be to give the guards a new collider that worked on trigger. To emulate a 4 directional line of sight I made a + sign out of the collider and prefabbed this onto the guards.
You can see above the original physics collider around the guard and the new trigger + collider. I’m honestly impressed with myself, I had a logical idea for once!
Currently this new collider didn’t do anything, so it was time to start cutting and pasting code together into something that would shoot a projectile. You can thank Kelly for reformatting the code into something a little neater, still getting used to ideal formatting.
As you can see we decided to use the multi-projectile shoot script and modify it. For simplicity we dialled the shots down to 4 each at an angle of 90º, so the guard would shoot up, down, left and right when the player crosses his path. Until we figure out something more complex this will do just fine.
The starting angle begins at 0º, the while loop begins and since the angle is not greater than 360º the projectile is instantiated and ‘fired’, the new current angle is 90º, less than 360º so fire again until we reach 360 and terminate the loop.
Other small changes made this week was adding tags for doors and the player. The guards new trigger collider was causing the player to exit the level after all flowers were collected and collided with a guard. Adding tags allowed us to add conditionals for the different tags, this way the player would ignore the guard triggers for exiting the level.
A small script was also added to change the door sprites after all flowers were collected to show to the player where they need to go. A nice little touch made easy thanks to the varied assets we’re using from kenney.nl.
All in all a solid week of progress, we’ll be adding more advanced guard scripts next week (line of sight) and will be shown a script for seeking objects to targets.