I made character movement using AddForce
. But I don't understand how to get the desired effect. I need that when I release a movement key (for example WASD) the character stops instantly or almost instantly, but when using AddForce it slides for a while after releasing the movement key.
For example
private void FixedUpdate()
{
moveHorizontal = Input.GetAxis("Horizontal");
moveVertical = Input.GetAxis("Vertical");
_direction = new Vector3(moveHorizontal,0, moveVertical);
_rigidbody.AddForce(_direction * _speed);
}
I don't want to change any Rigidbody or gravity properties, because it might cause other problems and affect other objects in the scene.
1 Answer 1
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 _direction = new Vector3(moveHorizontal, 0, moveVertical);
if (_direction.magnitude > 0.01f)
{
_rigidbody.AddForce(_direction.normalized * _speed);
}
else
{
_rigidbody.velocity = Vector3.zero;
_rigidbody.angularVelocity = Vector3.zero;
}
}
This will stop immediately if no input. When you press a key Horizontal or Vertical the value of it will be between [-1, 1] so the Vector3.magnitude
obviously > 0.01 and if you're not press anything then you can stop the Rigidbody
. It has been 2 years since my last code in Unity. If it wrong please let me know :v
-
\$\begingroup\$ May I ask why you deleted this answer? It looks reasonable to me, though I'd tweak the check to
if (direction.sqrMagnitude > 0f)
\$\endgroup\$2025年06月03日 23:39:29 +00:00Commented Jun 3 at 23:39 -
\$\begingroup\$ Something just through out my mind that it was wrong and I 'm going to install Unity and check again so I was temporarily delete my answer \$\endgroup\$Tiên Hưng– Tiên Hưng2025年06月04日 02:23:15 +00:00Commented Jun 4 at 2:23
You must log in to answer this question.
Explore related questions
See similar questions with these tags.
AccelerateTowards
method that applies forces to match a target velocity — including using forces to slow down and stop when the target is zero. This answer shows a simple version. This other answer shows a slightly more elaborate version where you can apply a stronger stopping force, while keeping the acceleration gradual when speeding up \$\endgroup\$