How can I improve this movement script?

I want to improve it, becouse my Player doesnt move smoothly. I wish he could move diagonally. Can you help me please?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {

    public float moveSpeed;
    public float jumpHeight;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        if(Input.GetKeyDown(KeyCode.W))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, moveSpeed);
        }
        if(Input.GetKeyUp(KeyCode.W))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(0,0);
        }

        if (Input.GetKeyDown(KeyCode.D))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
        }
         if(Input.GetKeyUp(KeyCode.D))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(0,0);
        }

        if (Input.GetKeyDown(KeyCode.A))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
        }
         if(Input.GetKeyUp(KeyCode.A))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(0,0);
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x,-moveSpeed);
        }
         if(Input.GetKeyUp(KeyCode.S))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(0,0);
        }
    }
}

Make a local Vector2 variable (call it velocity?) and set it equal to Vector.zero.

Now for each of your directions of motion, set ONLY the axis you care about, eg:

if you press RIGHT then set velocity.x = 1

If you press UP then set velocity.y = 1

Finally when you have checked all your keys, assign that velocity Vector2 variable to the GetComponent().velocity property once.

Adding onto this answer, this is a great time to try using GetAxis.
It seems you want a fixed speed without the built-in smoothing of GetAxis, so we’ll use ‘Raw’…
Also, it’s a good idea to cache the rigid body 2d.

Rigidbody2D rb;
void Awake() {
   rb = GetComponent<Rigidbody2D>();
}
void Update() {
   float h = Input.GetAxisRaw("Horizontal");
   float v = Input.GetAxisRaw("Vertical");

   Vector2 vel = new Vector2(h, v); // could simply create this from the 2 GetAxisRaw without 'h' and 'v'
   if(vel.magnitude > 1) vel.Normalize();  // prevent diagonal from being faster.

   rb.velocity = new Vector2(h,v) * moveSpeed;
}
1 Like