- Home /
How to move Character with AddForce
Hello Everyone. I wanted to create a physics based movement for my character.
[Header("Movement")]
public float playerSpeed;
public float jumpForce;
[HideInInspector]
public Rigidbody rb;
Vector3 x, z;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
//-----Inputs-----//
x = transform.right * Input.GetAxisRaw("Horizontal");
z = transform.forward * Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown(KeyCode.Space))
Jump();
}
void FixedUpdate()
{
Movement();
}
void Movement()
{
Vector3 movement = (x + z).normalized * playerSpeed;
rb.AddForce(movement);
}
void Jump()
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
I know I can use rb.velocity to set velocity but I also want to add force to the player from certain direction when certain key is pressed. The issue with rb.velocity is that when I am adding force with the movement key pressed the force is canceled as velocity is being overwrite.
Thats why I want to add force. If you have other method to solve this problem I will be grateful. Thanks for reading.
Answer by ryanmillerca · Jul 23, 2019 at 03:57 PM
I used this as a starting point for rigidbody player movement in Fossil Hunters and it worked very well, especially in our circumstance which involved the player constantly interacting with physics objects. Try it out! http://wiki.unity3d.com/index.php/RigidbodyFPSWalker
Hello @ryanmillerca unfortunately the link posted above isn't working anymore (at least for me) and I'd be very curious about that. Could it be possible for you to update it ? thank you very much!
Your answer
Follow this Question
Related Questions
Rigidbody movement conflict? 1 Answer
Why can't i addforce to a rigidbody? 2 Answers
RigidBody.AddForce not working 1 Answer
Movement using rigidbody.velocity to apply a constant force until stop 1 Answer
Setting a delay before dashing. 1 Answer