In this post , I will tell you how to add movements in 2d unity game. As you know movement is all about vectors. If you don't know what is vector then it is really bad. Vector is topic of physics go clear the concept of vector first then come back. So movement is all about vectors as in 2d game you have to deal with 2d vector that is x-axes and y-axes.  You can update position and do all movement stuff with the help of vectors. So in this post I will be sharing my script with you guys.



using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour
{

    private float CharacterMoveSpeed;
    private float DirX;
    // Start is called before the first frame update
    void Start()
    {
        CharacterMoveSpeed = 6f ;
    }
    // Update is called once per frame
    void Update()
    {
     
     DirX = Input.GetAxis("Horizontal") * CharacterMoveSpeed * Time.deltaTime ;
     transform.position = new Vector2 ( transform.position.x +  DirX , transform.position.y  ) ;
    }
}




In this script there are two variables, one is characterMoveSpeed which is speed of movement for character and DirX is for direction of movement. Input.GetAxis("Horizontal") is constant global variable which gives negative value if user press left arrow and positive value for pressing right arrow. You can change its setting ( Horizontal ) in input manager in unity or you create new input in input manager. Here is the photo of input manager. You can find it by going to edit then Project setting.


Input Manager
Input Manager




If you want to move character with constant speed then you should multiple Time.deltaTime with updated values, this will help to set the speed value constant in every frame per second. If game object is 2d then we will use 2d vector to update its position. To move character left or right, you need to increment or decrement x-axes, similar for top or bottom movement you need to changes value of y-axes. Increment will move character right or up while decrement can move character left and down. 


In order to use script, just create empty script and put following code I mentioned above and then put that script directly into character inspector. It will start working to move with selected input (left or right arrow).

Thanks



Previous Post Next Post