Unity Series - Part 2: Adding A Player And Scripting Movement

·

3 min read

Unity Series - Part 2: Adding A Player And Scripting Movement

Photo by Ma Joseph on Unsplash


Adding A Player Script


The first step is creating a player. For now I will be using a asset I got from the unity asset store called Tiny RPG Forest.

As you can see, I have imported it into my project and now we are ready for adding the scripting to the player.


Scripting - Moving The Player


The scripting of the play if fairly simple.

We are going to click on the player and press add component. From there we will type in "Player Movement" and hit enter twice so that we can create the script. Once you have done that, double tap on the new script we just created and it should open up Visual Stduio Code.

Inside of your script, we will start by adding some variables

public float moveSpeed = 5f;

    public Rigidbody2D rb;

    Vector2 movement;

moveSpeed - a float that is going to be used for our movement speed regarding the player

Rigidbody2D - list the Rigidbody of our player to involve physics in our movements

Vector2 - to access the x and y axis of our player in a variable

Now that we have all the variables we need, we can move on to scripting the inputs. You can get rid of the start method as it is not useful in this script. Inside of the Update method, we will list our Inputs for the horizontal and vertical axises.

void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");
    }

The final step is to update our player position every time it moves.

void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    }

As you can see, I have used the FixedUpdate method, which calls 50 times a second, making the movements more accurate. Here we get the rigidbody and MovePosition to move the object. Inside the MovePosition, we take the RB and grab its position, then add it to the Vector2 "movement," times it by the moveSpeed, and finally times it by Time.fixedDelatTime.


Adding New Inputs


After saving that file, we can go back to Unity and add in the elements that we just listed. moveSpeed should be set to the default of 5, but if you want to change that, you can. The other one is RigidBody2D, you can easily do this by dragging the RB of the player into that slot.

That will be all for the part. The next blog will be about animations and using them on our character


Conclusion


This will be the end of this blog but I hope that you learnt how to moe a character in a top down(issometric) game and tune in as I will be making more changes to the game and will be documenting them.