- Home /
Rigidbody.velocity not moving player
Problem: So as the title says I can't get the player character to move using rigidbody.velocity. I have also tried using addforce however the only one that moved was impulse which launched the player far away from the environment. The player being used is the prefab from the free asset package Robot Sphere.
Any suggestions would be greatly appreciated, Jonathan Palmer
Code:
public class Movement : MonoBehaviour
{
[SerializeField] private float movementSpeed;
private Rigidbody player;
void Start()
{
player = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetAxisRaw("Vertical") == 1 || Input.GetAxisRaw("Vertical") == -1)
{
player.velocity = new Vector3(Input.GetAxisRaw("Vertical") * movementSpeed, player.velocity.y, player.velocity.z);
}
if (Input.GetAxisRaw("Horizontal") == 1)
{
player.velocity = new Vector3(player.velocity.x, player.velocity.y, -1 * movementSpeed);
}
if (Input.GetAxisRaw("Horizontal") == -1)
{
player.velocity = new Vector3(player.velocity.x, player.velocity.y, 1 * movementSpeed);
}
}
}
are there movement constraints or is the rigidbody set to beeing kinematic? what is the value in "movementspeed"?
Answer by Arshww · Mar 27, 2020 at 06:19 PM
Hello! let me suggest you to use this peace of code, it's not tested but should work.. Of course, set movement speed to your preference.
private float movementSpeed = 500f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
///It's better to manage physics in FixedUpdate
void FixedUpdate()
{
//First, We should get values from inputs to make the ridibody know where to move
float Horizontal = Input.GetAxisRaw("Horizontal");
float Vertical = Input.GetAxisRaw("Vertical");
//Then we move the Rigidbody
rb.velocity = new vector3(Horizontal * movementSpeed, 0.0f, Vertical * movementSpeed);
//You can of course add some extra features:
//If inputs are equals to zero, then the player should be Idle:
if(Horizontal == 0 && Vertical == 0)
{
//Add an Idle Animation, maybe?
}
}
Hope this work! Remember to set your Rigidbody to Dynamic and check its constraints
I'd suggest to adapt to OP's correct carry of the y-velocity. In your current code the player can never fall.
Your answer
Follow this Question
Related Questions
When stopping Rigidbody.velocity 1 frame stutter C# 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Move player based on camera direction (MOBILE JOYSTICK) 0 Answers