Top Down Movement in Unity Tutorial

August 13, 2019

Unity Top Down Movement

Brackeys Tutorial

Youtube – TOP DOWN MOVEMENT in Unity!

By: Brackeys

This seemed to fit well with the Pokemon tutorials I was doing recently so I decided to give it a look. It’s been a while since I used Animator variables to control 2D animations so this was a nice refresher for that, but they also used Blend Trees which is something I had not seen before.

The initial script was very simple. This was a 2D Rigidbody setup, so it’s more physics based than the Pokemon tutorial I am doing. As usual for physics in Unity, they do the physics work in a FixedUpdate method, however, they still receive the input in a standard Update method. I always see you should do your physics in FixedUpdate to deal with frame rate variance, but had not seen anything specific about splitting up the input and physics into the two different Updates.

The Animator starts by adding two simple parameters: float Horizontal and float Vertical. The Blend Tree happens in a single state in the Animator for the Animator Controller for the player. When you right click and select “Create State”, you select “From New Blend Tree” instead of “Empty”. You can double click it to go one level deeper into this state node. It’s important to note the parameters apply here too, so they are useable throughout all the levels.

In this Blend Tree, there are three main factors to account for: the parameter, the thresholds, and the animations. You start with the parameter to check. You can then set “Motion Fields” which will hold an animation and parameter thresholds. It will then check the parameter relative to the thresholds set to determine which animation to play. This simple 2D walking animation set is a great example to show this off in a simple way, as it basically just switches between the 4 different directional walking animations depending on the combination of the horizontal and vertical parameters.

They then go back to the top level of the Animator to tie everything together. They make a transition from Idle to this Blend Tree, and vice a versa. This just makes sure to set a state for what to do when the player isn’t putting in any inputs.

Finally, to tie this new Animator setup in with the actual movement script and player input, they go back to the PlayerMovement script. The small addition needed here is simply setting the Animator parameters equal to the input gotten in the Update method.

Overall, this was a neat way to approach 2D movement in Unity a bit differently than I have before. The Animator blend tree definitely seems nice for keeping the PlayerMovement script cleaner and easier to read instead of cluttering it with a lot of input comparisons to determine different sprites and animations to use.

Using Coroutines to Control Animation in Unity

August 12, 2019

Coroutines for Animation Timings

Unity

Youtube – Coroutines and Animation: Beyond Beginner Unity Tutorials

By: Tom coAdjoint

For a Unity project, I needed to control the flow of my program to process an animation fully before moving on to the next operations. Timing concerns normally lead me to coroutines, so I looked into controlling animations with coroutines in Unity.

The approach I ended up using for a quick fix solution was just to use WaitForSeconds in Unity. I basically just had the operation start the animation and then WaitForSeconds approximately the duration of the animation (which needs to be hard coded in at this point), and then continue with operation. While this works, it feels a bit clunky and hard to work with. For example, changing out the animation will require changing the time accordingly every time. Also different animations will need different values entered individually.

I came across this tutorial linked above which seemed promising for a better animation timer, especially for game building purposes. Unfortunately, I don’t have a lot of experience programming animation related objects in Unity, so I was not able to fully grasp how this setup worked. I need to look into the already available methods and variables Unity provides when working with the Animator and Animation more.

The main coroutine driving everything here is IEnumerator WaitForAnimation, which has the following setup:

IEnumerator WaitForAnimation(string name, float ratio, bool play)
{
var anim = animation[name];

if(play) animation.Play(name);

while(anim.normalizedTime + float.Epsilon + Time.deltaTime < ratio)
yield return new WaitForEndOfFrame();
}

The overall premise makes sense. You input an animation name, a ratio of how much of the animation you want to play, and a bool to activate it. It was unclear which variables were created by the tutorial and which exist in Unity already. animation[name] appears to be an array reference, but I am unsure if this is how Unity normally deals with animations or if this was created separately. normzlizedTime is also new to me, but that does appear to be a built in time of animation reference.

It will take a bit more researching, but this approach definitely seems to be more general and useful if I can determine exactly how it works.

Learning from Pokemon Unity Tutorial

August 8, 2019

Unity Pokemon Tutorial

Setup

Youtube – Lets Make… Pokemon in Unity! – Episode 1 – Basic Setup World/Character

By: BrainStorm Games

As a big fan of Pokemon, I wanted to finally jump into this tutorial just to learn from what it has to offer. It could be very helpful for any 2D projects, especially those that are more RPG-based, and I imagine a lot of concepts can be carried over to 3D projects as well.

I am especially interested to see:

  • How they perform the movement in a way that’s consistent and easy to control
  • Setup of the overall “Pokemon” class structure to deal with many different options of very similar creature objects
  • How they deal with encounters (and the implementation of randomness)
  • Connected to points 1 and 3, how they structure the overall class for encounter areas
Using Tiles

Sometimes tiles can have a line between them even though they are connected, but this is normally caused by anti-aliasing. This can be turned off in the quality settings in Unity. Newer versions (I’m using 2019.1.12 currently) seem to have that disable initally in 2D projects.

Since we’re using tiles that are generally positioned pretty precisely, I thought this would be a good time to use Progrids again. This is perfect for continously placing all these tiles in exact incrementally different locations right next to each other. It is a bit awkward that the tiles get placed onto the intersection points of the grid as opposed to filling in the nicely made grid squares, but that’s just an aesthetic pain. It functions perfectly for this.

You can also achieve a similar effect to Progrids just normally in Unity by holding [Ctrl] while clicking and dragging to move an object. This can move the object one unit at a time.

Unity Controlling Coroutines

August 6, 2019

Controlling Coroutines

More Advanced Coroutines in Unity

Youtube – Unity3D – 2 Ways to Start & Stop Coroutines (the good & bad ways)

By: Unity3d College

Youtube – Unity3D – Using Delegates / Actions as Callbacks in Coroutines

By: Unity3d College
1st Tutorial

This first tutorial is one I’ve looked at before, and it makes more sense now when I want more accurate control of a coroutine in Unity. Basically you can create an IEnumerator variable that can just hold the coroutine you want to run. This same variable can be checked for being null as a way to determine if it is already running, which can be helpful to ensure only one instance of the coroutine is running at a time.

This also suggests a different approach than normal for creating a more accurate timer in a Unity coroutine. Instead of counting a timer up or down with Time.DeltaTime, they set a float value to Time.time when the coroutine is started, and then check if difference of the current time (Time.time) and that set start time is greater than your intended timer value.

2nd Tutorial

This was a bit more advanced, and I need to look more into Unity Actions to fully understand how this works, but I think I got the general concept. It appears the basic premise is using an IEnumerator which takes on a method (methods) as a delegate input to ensure that a certain step is completed before running the input delegate (method(s)).

For example here, they wanted to replace an image but they wanted to ensure that the www object was obtained first to use for that method. Since a delegate was used, they also showed the flexibility of how the same foundation could support different methods.

What I am a bit confused by here, is how the ReplaceImage method that is set as the delegate in the LoadImage IEnumerator gets its input. It requires an input of Texture2D but I don’t see if or how that is set. I believe this may be my lack of knowledge on either Actions or Delegates in Unity, so I’ll need to look into that.

Unity Composition and Inheritance

July 29, 2019

Unity Composition

Composition vs Inheritance

Youtube – Unity Architecture – Composition or Inheritance?

By: Unity3d College

I was looking to use inheritance with an overall parent abstract class to create a few simple scripts, but was having some trouble getting it setup properly. When looking into how to approach this better, I came across the concept of “Composition vs Inheritance”. This is the first time I heard the word composition, but it appeared to be the idea in Unity of creating a bunch of small scripts that perform specific types of functions that can be placed on objects in a varied structure style to create the proper type of object you want.

I thought this was a neat concept that made a lot of sense in Unity, so I ended up using this idea to approach the issue I was working on. This got me into using RequireComponent(typeof) in Unity, which I’d seen before but never really used. This seemed to be a nice feature to keep track of with a composition style approach since there will probably be a lot of cases where certain components will need others to be there, and this is just a good practice to make sure you don’t have any issues when setting up your structured object.

Updating Waypoint System in Unity

July 19, 2019

Updating Waypoint System

Starting with a base waypoint system I created with the Brackeys tower defense tutorial, I wanted to update it so that the overall path could be altered at run time. Basically, I didn’t want objects traveling along the waypoints to travel the full length everytime. I needed them to sometimes travel part way, sometimes more/less, sometimes the full way.

I decided I would have the main script holding the general waypoint information to hold the value for where objects should stop traveling. This way all objects could reference this for how far they should travel, and I could have anything else just change this single value to update where everything is going. This was as simple as adding an int value called currentEnd to this main script, Waypoints. Then I added the methods GetCurrentEnd (to return currentEnd) and SetCurrentEnd (to change the currentEnd value).

Next was updating the Waypoint_Movement script, which is attached to the objects moving along the waypoints to tell them how/where to move along the waypoints. They were originally moving from waypoint to waypoint until they reached the end of the Waypoints array (Waypoints.points.length – 1, the length of the waypoints array minus 1). This causes them to travel until they hit the end of the array. This was simply changed to check for [Waypoints.GetCurrentEnd() – 1] so they would only move to a waypoint determined by the currentEnd value at the time.

Finally, other scripts were able to add in the SetCurrentEnd() method call from Waypoints to their current functionality to have it basically update the length of the waypoint path further objects would travel.

Outline Shader in Unity

July 3, 2019

Outline Shader Tutorial in Unity

Youtube – Shader – Smooth Outline – [Tutorial][C#]

By: N3K EN

As someone with very minimal shader experience in Unity still, this step by step tutorial is nice for just getting a feel for how shader code is setup while also creating a useful effect for certain art styles or attention drawing practices. It simply creates an outline around 3D objects of various color with variable width.

Creating a First Person Camera Controller in Unity

July 3, 2019

Creating Basic FPS Camera Controller

FPS Controller in Unity

Youtube – How to construct a simple First Person Controller with Camera Mouse Look in Unity 5

By: Holistic3d

This first tutorial is a good example for setting up the most basic type of first person camera in Unity. Since the project I was using didn’t need a character at all and I was just attaching this directly to the camera, I needed to make some slight modifications to have it setup properly. This is because I didn’t have a parent object to apply the second type of rotation to. This just required me to set both rotations in both directions at the same time (since setting one and then the other to the exact same object had the second rotation constantly overriding the first).

This camera had a slight issue though where it moved relative to wherever the mouse starts on the screen. While I was just creating this camera controller for debugging purposes for an AR project, this would be an issue to investigate in the future if you actually wanted to use the controller for a game. Just implementing something simple using the mouse’s initial position relative to screen space somehow.

Tower Defense Tutorial Fixing Scene Manager

Tower Defense Tutorial Fixing Scene Manager

June 19, 2019

Tower Defense Tutorial Project

Fixing Problems with the Scene Manager

To help get back into the groove of working on my tower defense project, I went over some scripts that I thought might help fix problems and listed out how they reference each other. (Lower placed scripts reference the higher ones)

Script Reference List

  • PlayerStats
    • LevelPlayerStats
  • WaveSpawner
    • WaveInformation
    • LevelManager

Then I got working on the problems with the scene manager and the method call timings between the different scenes that were giving me errors. There are a lot of issues when references trying to be called before variables are properly set in different scenes, and this offset is leading to a lot of errors where the checks are checking against default values like 0 and null as opposed to their properly set values. So once again, I made a list of problems as I encountered then and possible fixes I tried, including the ones that finally worked and stuck for now.

SCENE PROBLEMS

Problem

Menu buttons do not work

  • Going back to the level select menu screen is not working on either button, so Menu() method must be incorrect
  • The for loop to deactivate level buttons the player should not have reached yet was given the wrong value to start with when reactivating the scene
    • it was setting a value to the active scene’s index and adding that to the for loop check for the level select button array
    • this value was initializing at 0 the first time through for some reason (another scene timing error), but was then being set to 4 when returning (which I believe is the level scene’s index, so this is another scene timing issue, but being properly set to 3 [the index of the level selection scene] would have been bad as well)
Solutions
  • Solution: Just removed the addition of the current active scene build index all together; I think this was added at some point to process the correct level build indices, but that is no longer needed.



Problem

Retry for a level does not work

  • Clicking retry does unload and reload the current level scenes, but it is done so improperly and the timer does not count do to start the first wave ever
  • Just ever unloading a level scene and trying to load it again has the same problems
    • This indicates something is not being properly reset the second (or more) time the scene is loaded
    • Look to individual Level scene and Base scene (created for all levels), especially in Start type methods
    • EnemiesAlive and WaveIndex are not resetting to 0 when scene is unloaded
      • EnemiesAlive specifically is one of the checks to see if a wave should be spawned (spawns a wave when the value is at 0 to make sure the previous wave was defeated)
Solutions
  • Potential Solution: reset these values to 0 when level scenes are loaded
    • tried this by creating a ResetWaveSpawner method in the WaveSpawner itself, then having something reference this on Start with something that is created on Level load
    • started method in Start method of LevelManager script
      • this actually worked for going back to the menu and then trying the level again, but retry still did not work properly
      • I figured this meant the scenes might be loaded/unloaded differently, so I checked my sceneManagerLite and sure enough, the level selection from the menu needed to load both the Base and Level scene, but retry was JUST unloading/reloading the Leve scene, not the Base scene, which is where the LevelManager is located that is resetting the wave spawner on Start
  • Potential Solution: just have the reset called in the Start method of something in the Level scene itself
    • This did allow the level to start properly when returning to the menu and coming back, or with the simple retry. However, there were still some other problems. Now if you beat a level, every time you returned the game won screen would come up and the game would still play in the background. Leaving the level during play and coming back (by menu or retry) would also change the “Rounds Survived” counter at the end, indicating something with the wave counters was not resetting properly.



Problem

Beating Level Once Beats it Forever

  • After beating level, game won screen comes up immediately when going back to the level
  • Back to our game winning bool checks, appears that the WavesFinished bool is not properly reset when returning to a level. This should be false every time the player starts the level, and get set to true when they win. This is happening correctly, but it is never reset to false.
Solutions
  • Possible Solution: reset the WavesFinished bool in WaveSpawner with proper scene timing
    • Actually just added this to the newly created ResetWaveSpawner method I created to deal with the previous resetting issues and this fixed it



Problem

Wave Spawning Coroutine is Off

  • Resetting a level during the spawning of a wave has the rest of the wave spawn immediately (at the beginning of the newly reset level) as well as spawning the second wave (skips the spawn of the first wave all together)
  • This indicates the coroutine spawning the wave might need manually jumped out of on reset and that the wave index is being messed up by their being enemies remaining