'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 1:[1]
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);
}
Solution 2:[2]
change the sideways force if you dont want it to go super speed:
> public Rigidbody rb; private float forwardForce = 2000f; // This is
> how fast the player goes forward public float sidewaysForce = 500f;
> //Change the number here to something lower.
//Add this to go forward and backward
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fuczak |
| Solution 2 | tacosthebadprogrammer |
