Rigidbody Addforce Not Working
I Have The Following Script For a Simple Rigidbody Movement, but When I Press Keyboard Keys It Doesn't Move At All. Keep In Mind That I Didn't Change Any Of Rigidbody's Settings. Code:
public class CharacterMovement : MonoBehaviour
{
bool IsForward, IsRight, IsLeft, IsBackward;
Rigidbody rb;
public float MoveSpeed = 10;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKey(KeyCode.A))
IsLeft = true;
if (Input.GetKey(KeyCode.S))
IsBackward = true;
if (Input.GetKey(KeyCode.D))
IsRight = true;
if (Input.GetKey(KeyCode.W))
IsForward = true;
}
void FixedUpdate()
{
if (IsLeft)
{
rb.AddForce(-transform.right * MoveSpeed * Time.deltaTime);
IsLeft = false;
}
if (IsBackward)
{
rb.AddForce(-transform.forward * MoveSpeed * Time.deltaTime);
IsBackward = false;
}
if (IsRight)
{
rb.AddForce(transform.right * MoveSpeed * Time.deltaTime);
IsRight = false;
}
if (IsForward)
{
rb.AddForce(transform.forward * MoveSpeed * Time.deltaTime);
IsForward = false;
}
}
}
Continuous inputs are fine in fixed update, you can put them there, also put a debug.log in each if statement in the fixed update...
Answer by arash28134 · Aug 21, 2021 at 01:30 PM
The Whole Problem Was That I Had To Pass In The ForceMode Parameter (ForceMode.Impulse) At the end of each AddForce method. Also keep in mind that you SHOULDN'T use transform for directions (forward, right, etc.) Since It is in local space and instead, use Vector3.left/up/etc. That way the gameobject will have some weird movement. Have A Nice Day!
Your answer
Follow this Question
Related Questions
How to throw an object towards a hit.point in first person? 0 Answers
Conserve some of Rigidbody's speed when turning. 0 Answers
I want stop the rotation when the player run around 0 Answers
Avoid varying output on same amount of force applied to a Rigidbody2D. 0 Answers
Steering a Spaceship using rigidbody 0 Answers