Search code examples
c#visual-studiounity-game-enginegame-enginegame-physics

Player Movement in Unity 3D


So I am new at Unity and I am following a YouTuber named Brackeys but when I execute his code for movement of the character my character doesn't go forward or backward it does go Left and Right but in super speed. I am new at this so I don't know much about this. Here is the code :

using UnityEngine;

public class PlayerMovement : MonoBehaviour {

public Rigidbody rb;

private float forwardForce = 2000f;  
public float sidewaysForce = 500f;  

void FixedUpdate()
{

    rb.AddForce(0, 0, forwardForce * Time.deltaTime);

    if (Input.GetKey("d"))  
    {

        rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

    if (Input.GetKey("a"))  
    {

        rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

    if (rb.position.y < -1f)
    {
        FindObjectOfType<GameManager>().EndGame();
    }
}

}


Solution

  • I think what you are missing here is movement along z axis.

    
        if (Input.GetKey("w"))  
        {
    
            rb.AddForce(0, 0, forwardForce * Time.deltaTime, ForceMode.VelocityChange);
        }
    
        if (Input.GetKey("s"))  
        {
    
            rb.AddForce(0, 0, -forwardForce * Time.deltaTime, ForceMode.VelocityChange);
        }