- Home /
How to stop player velocity completely
I have made a script that makes the character move. The problem is that the character is sliding around. I want to set velocity to 0 anytime the right buttons arent pressed. What line of could could do that. Thanks for any guidance and explaining. Herses the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
private bool moving;
[SerializeField]
Vector3 v3Force;
[SerializeField]
KeyCode keyPositive;
[SerializeField]
KeyCode keyNegative;
void FixedUpdate()
{
if (Input.GetKey(keyPositive) || Input.GetKey(keyNegative))
{
moving = true;
}
else { moving = false; }
if (moving)
{
if (Input.GetKey(keyPositive))
GetComponent<Rigidbody>().velocity += v3Force;
if (Input.GetKey(keyNegative))
GetComponent<Rigidbody>().velocity -= v3Force;
}
else
{
}
}
}
Answer by JohnnySix · Feb 12, 2020 at 09:11 PM
GetComponent<Rigidbody>().velocity = Vector3.zero;
Should do it, in your else bit.
I'd maybe assign the Rigidbody in the Start rather than doing a GetComponent reference each time too.
Thanks for your answer. I tried your solution and it partly worked, the problem is that the player dosent move forward and backwards anymore, only to the sides. What do you think i did wrong?
And in case that doesn't stop one's body completely, also add .angularVelocity = Vector3.zero
(e.g. a rolling ball might otherwise keep moving again). Plus, consider increasing the Drag value in the Rigidbody options for a more natural, smoother halting of movement (after doing so, AddForce()
strengths may need to be increased).