Unity - Movement and Boundary


In terms of coding we first created a C# script called PlayerController which will contain the movement of the ship.

A fix update function was created. This function is called every fixed framerate frame, if the MonoBehaviour is enabled.

void FixedUpdate ()
    {


Two float types variables moveHorizontal and moveVertical.

public float moveHorizontal = 0;
    public float moveVertical = 0;


Within FixedUpdate the two floats are set to the corresponding input axis.

void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");


Then I created a new vector3 variable called movement where I set the x, y, z variables to the appropriate move variable.

Vector3 movement = new Vector3 (moveHorizontal0.0fmoveVertical);

By doing this sets up the ship (the players movement). Because it is essentially a 2D arcade like game, the player only needs to move up, down, left, right.


Referencing the game objects rigidbody component set the velocity variable to our movement variable.

We want to be able to change the speed of the spaceship through the inspector window which was done by adding more code to playercontroller script to allow this. I declared a new public float name speed.

public class PlayerController : MonoBehaviour
{
    public float speed;


Then multiplied the movement variable by the speed variable and set speed to a appropriate value.

rigidbody.velocity = movement * speed;

A very important part of creating this game is setting boundaries, as if they were not created our ship would be able to keep moving until...well... the game breaks. A new class named Boundary is created. I declared the float variables xMin, xMax, zMin and zMax.

public class Boundary
{
    public float xMinxMaxzMinzMax;
}



I had to set the position of our ship to be clamped between our minimum and maximum variables, but amend the script so that the clamp max and min reference the correct variable.

rigidbody.position = new Vector3 
            (
                Mathf.Clamp (rigidbody.position.xboundary.xMinboundary.xMax), 
                0.0f
                Mathf.Clamp (rigidbody.position.zboundary.zMinboundary.zMax)
                );
        


Once this coding was done, when going back to the inspector it now gives me the option to change the speed of my player, and boundary size of my game. I set the boundary to allow space at the top for my asteroids to fall through.


No comments: