Pokemon Unity Tutorial – More Pokemon [Pt.6]

August 19, 2019

Unity Pokemon Tutorial

Encounter List Creation

Youtube – Lets Make… Pokemon in Unity! – Episode 6 More Pokemon!

By: BrainStorm Games

This tutorial is about actually creating BasePokemon GameObjects and using them as a prefabs. The general prefab structure is pretty simple. The object is a SpriteRenderer (with the pokemon’s sprite) and has a BasePokemon script attached that just has all the base stats filled in in the editor, along with typing in the name and also hading a sprite reference here.

We created 5 different types of this prefab for different pokemon objects and used those to populate the GameManager BasePokemon list. It turns out this list won’t be holding every pokemon that exists in the game, this will just the list of possible encounters in the current area.

The method for encountering pokemon included creating an EmptyPoke prefab as well, which acts as a placeholder that becomes one of the referenced Pokemon objects from the current GameManager list. The battle instantiates this EmptyPoke object, and then uses the reference from the randomly selected Pokemon object from the list to basically add a BasePokemon component to this EmptyPoke object and copy all the relevant data over to it.

Finally, they added some transform objects to locate your pokemon and the opposing battle pokemon in the battle scene. These objects are just referenced as where to instantiate Pokemon objects (and as a result, their sprites).

Testing and Debugging

Problem 1: Generating Empty Lists that Were Being Accessed

I was getting an error that GetRandomPokemonFromList from attempting to access an array element out of the bounds of the current list being given to it. It turns out this is because I only put VeryCommon and Common rarity pokemon as options to be found, so when any other rarity (Rare, Semirare, VeryRare) were being rolled for the encounter, it was defaulting to trying to access the first element of an empty list.

Solution

I was able to solve this by adding a check for an empty list and having the method return null in that case, then the rest of the methods using this data would check if it was null first before performing their actions, so they would only proceed if they had an object to work with first.

Problem 2: Missing Encounters

I added my own EndBattle method to the GameManager script just to make testing multiple encounters easier and found an issue where it did not seem like every pokemon in the list was coming up as an encounter. I know RNGs can be a bit repetitive, so I tested for a while but it was clearly missing some encounters.

Solution

It turns out the Random.Range int they were using with bounds of 0 and list.count – 1 did not need the (- 1) since the high bound is an exclusive bound. With the (- 1), one pokemon from each rarity tier was being left out as an option. Removing the (- 1) fixed my issue, and all pokemon were appearing (eventually).

Pokemon Unity Tutorial – More Pokemon Integration [Pt.5]

August 19, 2019

Unity Pokemon Tutorial

Class Data Management

Youtube – Lets Make… Pokemon in Unity! – Episode 5 – More Pokemon Integration

By: BrainStorm Games

This tutorial focused on creating the Player class and increasing the functionality of the BasePokemon class.

The Player class contained a list of OwnedPokemon, which was a newly created class within the Player script.

The BasePokemon class added some new features to work with evolution. The PokemonEvolution class was created, which held a BasePokemon that is the next evolution and an int for the level at which the evolution should occur. A PokemonEvolution variable was created within the BasePokemon class which would hold a reference to what pokemon a single one could evolve into.

There was also a lot done with the GameManager script. A PokemonMoves class was created that would provide the foundation for all the different types of attacks in the game, as well as a new MoveType enum, which categorized the moves (as physical, special, or status). There was also a Stat class that was created that just held a float for a minimum value and a float for the maximum value. The GameManager class itself also got a list of BasePokemon called allPokemon, and a list of PokemonMoves called allMoves. I am assuming these will just be used to hold some style of reference to every unique type of pokemon and move in the game.

The GameManager class also contained the methods for determining which Pokemon is randomly encountered in battles. A List method, GetPokemonByRarity, was created which basically takes an input of a Rarity enum and then looks through the current list of allPokemon and creates a new list with only those that have the same rarity value as designated by the input Rarity. Then another method, a BasePokemon method called GetRandomPokemonFromList, simply takes a BasePokemon list input (the list created by GetPokemonByRarity) and then randomly chooses one of the BasePokemon from that list and returns it. This combinations works to determine the specific pokemon encountered when calling a random encounter.

Again, things seem to be run a bit inefficiently (for example, populating this rarity list every time a battle is encountered) but I’ll be interested to see where it leads. This tutorial was a lot of setup that will make more sense once the system gets put in motion.

Pokemon Unity Tutorial – Player Movement [Pt.4]

August 15, 2019

Unity Pokemon Tutorial

Random Encounters

Youtube – Lets Make… Pokemon in Unity! – Episode 4 Encountering Pokemon in Long Grass

By: BrainStorm Games

This tutorial sets up the random encounter mechanic. This starts with the script LongGrass, that deals with 2D colliders to allow for a probability check when the player collides with certain tiles to see if they encounter a random battle and what is encountered.

The setup places a 2D box collider on each LongGrass tile that is a trigger. The player character has a 2D box collider (not as trigger) and a RigidBody 2D component. They just set the gravity scale of the RigidBody 2D to zero and that was it. These seems like an improper time to use a RigidBody 2D component as we’re just using it to detect a trigger collision.

I also tried modifying some values in the RigidBody 2D so it fit the situation better, but none of them interacted with the LongGrass colliders properly. I tried making the Body Type “Kinematic” instead of “Dynamic”, as well as checking off “Simulated”, but neither of these collided with the LongGrass triggers at all. In testing this, I placed a Debug.Log in the OnTriggerEnter2D encounter method just to make sure it was detecting the collisions, and I noticed a bug where moving left or right in the LongGrass was actually calling for an encounter chance twice for some reason. This also did not apply when moving up or down, just for left and right motion.

The way they switch from the overworld game to the battle scene also seems improper. They aren’t seperate scenes, they are just two different cameras placed in different locations in the scene space. The transition from the overworld to an encounter just turns off the overworld camera and turns on the battle camera. This seems sloppy and cluttered as you then have everything running in a single scene at all times.

Another note I did not like was that the LongGrass gets the GameManager component by tag. They created a “GameManager” tag for the GameManager and that is what they use to reference it and grab its script from other scripts. I am becoming less of a fan of tags as I work with various Unity projects as they are annoying to keep track of and finicky in code since they require typing an exact string value in. This can be lessened by creating a string variable to hold the tag name in your script so at least you only need to type it out properly once for that script, but it still seems to be a pain to work with and error prone, not to mention difficult to modify.

Tutorial – Creating a Realistic Boat in Unity

August 14, 2019

Realistic Boat Physics

Unity

Harbrador – Make a realistic boat in Unity with C#

By: eriknordeus

As someone interested in using real world physics and applying it with Unity’s physics engine, this tutorial just looked very interesting and promising. It appears they do a lot of work determining buoyancy as well as air and water resistance using the actual mesh of an object. They also split the code up in a nice way, separating a lot of the math into its own class to keep scripts organized and easier to use/read, so I wanted to look into that organizational setup. Overall, this is just a cool project that has a lot of factors I want to learn more about (physics in unity, organizing scripts, applying real world concepts to Unity/games).

HFFWS Moving Platform Tutorial

August 13, 2019

Human Fall Flat Workshop

Moving Platform Tutorial

Youtube – Moving Platform Tutorial in Unity for Human Fall Flat

By: Gotcha McFee

To start, they just went to the IntermediateLevel 1 scene to grab a copy of the moving platform prefab from there. They just placed this in a prefabs folder to use later.

This moving platform has a ton of script components on it, but the main one they focused on was called “Signal Math Nul”. Changing the second input value here changes how quickly the moving platform changes directions. A high value will make it go back to start very quickly, where a low number will take longer (and if it’s low enough, it will actually wait at the end point for some time before coming back).

Next, they showed that the child object, Axis, controls a lot about how the platform moves. By rotating this object, you can change the direction the platform moves. The other simple variables they show are:

  • Min Value: Normally just keep at zero
  • Max Value: Changes how far platform can move in given direction
  • Max Speed: Changes the top speed the platform can accelerate to
  • Max Acceleration: Changes how quickly the platform changes speed

These variables are pretty self-explanatory, but there are a few issues to note with them. Going back to the first problem where a platform that changes directions too quickly won’t even reach its maximum value, this needs to be checked when you change a platform’s Max Value. If you change this without giving it more time to change directions, it may not be ending up where you would plan on. Max Speed and Max Acceleration are values that need tested in game as they will contribute force and momentum to players that are on the platform. Having too high of values here can throw players off the platform and make it difficult to stay on.

Finally, they show that you can take this underlying foundation and place it on any object to make it move around. They child a new object to this entire setup and just turn off the old mesh components, but it’s actually easier to just change the base platform object’s Mesh Filter and Mesh Collider to the object you want (and then update the Mesh Renderer to fit this new mesh). This lets you use any mesh as a moving object.

HFFWS Object Instantiation and Setting Their Node Values

August 13, 2019

Human Fall Flat Workshop

Instantiating Objects with Nodes

Youtube – Moving Platform Tutorial in Unity for Human Fall Flat

By: Gotcha McFee

I just wanted to reference this tutorial again as this is how I got the moving platform in the first place for HFFWS. This also shows why I am interested in the specific components and their values when instantiating the object. This object also has a lot of node graph involvement, which is a big part of HFFWS in general, so it shows why being able to control their values in script is so necessary.

Creating Object Spawner

I wanted to create a script that could take some of these HFFWS prefabs and start spawning them with various values for their variables to see if I could produce varied objects in real time in the game.

This script needs to be able to:

  • Take a prefab reference
  • Access certain components (or children’s components)
  • Access the parameters of the components(s)
  • Randomly set them (within a given threshold)
  • Create instances of the prefab with these given values

The components for MovingPlatformVertical that we need access to are:

    Parent

  • Mesh Renderer
  • Mesh Filter
  • Mesh Collider
  • Signal Math Mul (Script): In 2
    Children (Axis)

  • Transform (Rotation)
  • Linear Joint
    • Max Value
    • Max Speed
    • Max Acceleration

It turns out SignalMathMul and LinearJoint are both part of the HFFWS .dll file. You can gain access to these classes in script however with the namespace “HumanAPI”. So at the top of your Unity C# script, you just need to add “using HumanAPI” to reference this namespace to create variable references for these classes.

The next issue I ran into however was attempting to set node values within script. SignalMathMul uses the node system, and I wanted to change the In 2 value of this component in script. By creating a variable reference for a SignalMathMul object, I saw there was simply a variable I could access within it called “in2”, which seemed like the variable I was looking for. Trying to set this as a float, I got an error telling me this was actually of type NodeInput. After creating this object, I looked at the methods and variables available and found one simply called “value”. So I tried setting the value of my number NodeInput to 0.5f, and then setting this signalMathMul.in2 to number (in an attempt to set the input 2 value of the signalMathMul component to 0.5f) but this just resulted in 0 at run time.

TESTING

I think that something with the whole Net Body setup may be causing issues, as this may not like values of these components being set at run time. This may be causing some value discrepancy for a very brief moment that when the networking system sees it it just defaults values to zero.

Initially, I was trying to instantiate a new moving platform with the given SignalMathMul values. I then tried to just alter the values of an existing in scene platform with the script. This also appeared to fail at first, as the inspector showed a value of 0 again. With further testing, this setup does appear to actually set the internal input node value. This change is not reflected in the Unity editor, but when play testing it did change the behavior of the platform. Upon further inspection in the node graph, it could also be seen here that the value was actually being set to that given in the script. I then went back to use the exact same setup but with instantiation again, and this did not work still. Again, this just set the input to zero. I checked in play mode in the updating node graph, and this confirmed it was actually set to a value of zero.

I then tried instantiating the object, and then changing its input values. This created an instance of the prefab with its default values just fine. The platform was moving properly. This however did not update the platform values with the scripted values.

SOLUTION

Since none of these approaches with setting in2.value to a number were working, I checked the methods and variables available again and saw there was also an initialValue variable for the Node Input class. I then tried setting in2.initialValue instead with my instantiated platform and this worked as intended. The value was properly set (in editor as well as in the node graph) and the platform’s moving behavior changed accordingly. The resulting script looks as follows:
public GameObject movingPlatformPrefab;
private SignalMathMul signalMathMul;
private LinearJoint linearJoint;

private void Awake()
{
GOInstantiatePlatform();
}

private void GOInstantiatePlatform()
{
GameObject newPlatform = (GameObject)Instantiate(movingPlatformPrefab);

newPlatform.GetComponent().in2.initialValue = 1.2f;
}

I left the extra component references in for later if I need them, and I was doing the instantiation in Awake through testing in case spawning it “later” was doing something weird with the networking scripts. I tested running it in Start instead and this also worked just fine.

Pokemon Unity Tutorial – Player Movement [Pt.3]

August 13, 2019

Unity Pokemon Tutorial

UI and Pokemon Class

Youtube – Lets Make… Pokemon in Unity! – Episode 3 Basic Pokemon and UI

By: BrainStorm Games

This tutorial covered the very basics of starting to get the UI setup in the game, as well as starting the overall base Pokemon class. The UI portion was just grabbing an image and setting it as the image for a Unity UI Panel. To help present the image in a certain way, they did go into the sprite editor to apply an all around 4 pixel border to the image.

The base Pokemon class started with two enums, this time for rarity and type. This class, BasePokemon, also references an outside enum that was created called BiomeList, which will set out the different types of environments a Pokemon can be found in. Other than these enums, the rest was just preparing the class by setting up a lot of the variables, like the Name, image, and all the stats (like hit points, attack, and defense).

Pokemon Unity Tutorial – Player Movement [Pt.2]

August 13, 2019

Unity Pokemon Tutorial

Player Movement

Youtube – Lets Make… Pokemon in Unity! – Episode 2 Basic Player Movement

By: BrainStorm Games

Player movement in the overworld of Pokemon games is tile based. To emulate this, the tutorial uses a Coroutine which can move the player a full tile at a time while locking the player out from further inputs until the player character has completed its full tile of motion. It also uses a simple setup where it reads the player’s horizontal and vertical input, but checks which is greater and reduces the other to zero to ensure the player is moving only on the two intended directions.

Since the player is a 2D sprite, they used an Enum setup to tie certain sprites to certain movement directions. This way it would look like the character is facing the direction they are moving. This setup had the 4 directions (North, South, East, West) for the Enum Direction. The player’s input would set the Direction variable, currentDir, to a corresponding direction. This would then be referenced in a switch case to determine which sprite to display for the character’s SpriteRenderer at the time.

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.