- Home /
Moving a player with Rigidbody
Hello everyone, I want to create a physics based movement, I am also using unity for quite sometime and always use Rigidbody.velocity or Rigidbody.MovePosition to move the player.
First thing I want is to move the player with tight controls example when user press button movement key it starts moving instantly and when released it should stops instantly too. Second thing I want is to add force in certain direction when user press ability key.
First I went with MovePosition but it doesn’t change the actual velocity of the player. Then I try to change the velocity of the player directly, but that’s where I meet with a problem as when player is not pressing the movement key it’s velocity is zero and AddForce doesn’t work when user press ability key.
Answer by Ak0rn · Jul 10, 2019 at 10:58 AM
The below code should do what you want.
public RigidBody playRB; //Put your player's rigidBody in here public float runSpeed;
float movement = Input.GetAxis("Horizontal"); if (movement > 0 || movement < 0) { ; playRB.velocity = new Vector3(movement * runSpeed, playRB.velocity.y, 0); }
Thanks mate just one doubt: If I press the key player gets some velocity and when key is released it’s velocity will be not be zero, if I put else statement on which velocity will be zero then I will not be able to AddForce as it get zero when key is not pressed.
What is the condition required for the addForce part?
So if you are moving in a certain direction and press the ability key it add force in that direction but if you are not moving then I want to add force in the direction player is facing and sometimes in opposite direction.
Answer by Z-ion · Jul 13, 2019 at 01:11 PM
This is the code I am using
void Update()
{
float x = Input.GetAxisRaw(“Horizontal”);
float z = Input.GetAxisRaw(“Vertical”);
if(x!=0 || z!=0)
{
Vector3 movement = new Vector3(x,0,z).normalize * speed;
Vector3 yTemp = new Vector3(0,rb.velocity.y,0);
rb.velocity = movement;
rb.velocity += yTemp;
}
if(Input.KeyDown(KeyCode.Space))
rb.AddForce(transform.forward * 100);
}
When I move with the WASD key then it works but as soon as I let go the key the velocity doesn’t go to zero and move in that direction. Also if I remove IF statement then when I press Space key to add force it add but in next frame it becomes zero again and don’t have any effect
Can someone help me out and thanks in advance.
Input.Get$$anonymous$$eyDown() returns true when you press it and in each frame, it resets its value and it will go to False state. so you need to press it again.. ins$$anonymous$$d use Input.GetAxis() and keep the button pressed for continuous force