0
\$\begingroup\$

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.

DMGregory
140k23 gold badges256 silver badges392 bronze badges
asked Jun 1 at 3:20
\$\endgroup\$
1

1 Answer 1

0
\$\begingroup\$
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

answered Jun 3 at 18:08
\$\endgroup\$
2
  • \$\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\$ Commented 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\$ Commented Jun 4 at 2:23

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.