- Home /
How to move Character with Addforce?
I'm trying to make a physic based Rigidbody movement, which adds force to the rigidbody without completely change the velocity (I'm creating a portal clone). I found this: http://wiki.unity3d.com/index.php/RigidbodyFPSWalker but it doesn't work in the air. Is there any way to solve this?
Answer by GDGames0302 · Jan 30, 2021 at 04:25 PM
Hi. You can do someting like this: (I modified only the Update function and removed the grounded condition to move even if the character is not grounded and I added the grounded condition only in the jump function)
void FixedUpdate () { // Calculate how fast we should be moving Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); targetVelocity = transform.TransformDirection(targetVelocity); targetVelocity *= speed;
// Apply a force that attempts to reach our target velocity
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
// Jump
if (grounded && canJump && Input.GetButton("Jump")) {
rigidbody.velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
}
// We apply gravity manually for more tuning control
rigidbody.AddForce(new Vector3 (0, -gravity * rigidbody.mass, 0));
grounded = false;
}
Thanks for your answers, but this wasn't my problem. I didn't describe it well. If you remove the ground condition, the velocity will be reset.
Your answer
Follow this Question
Related Questions
Moving rigidbody (Player) with addForce or Velocity ? 1 Answer
Implementing Counter-Movement 0 Answers
how to have a fixed movement using rigidbodies without animations 0 Answers
Smooth dashing issues 0 Answers
Rigidbody wont stop moving!!!! AGH!! 2 Answers