I've been using the transform property for movement so far and that left my Physics a little choppy on collision. To counter this I switched movement using Rigidbody.velocity. This is a sample of my code.
//Start
rb = GetComponent<RigidBody>();
jumpForce = 5;
//Update
horizontalInput = Input.GetAxis("HorizontalInput");
Vector3 movement = new Vector3(horizontalInput, 0.0f, 0.0f);
rb.velocity = movement * speed;
this worked when it came to left and right, however when I want to jump I use this function and my character does not move, is there something wrong I'm doing or am I too much of a beginner to understand?
if (Input.GetKeyDown(KeyCode.UpArrow)) {
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
CodePudding user response:
Looks like you're overriding the velocity when you do horizontal movement so the jump velocity has no effect. You should use rb.AddForce()
for horizontal movement too.
You have to be careful not to add too much force though. For an example see this answer.
CodePudding user response:
Vector3.up
is the same as new Vector3(0f, 1, 0f)
and since X and Z axis are 0 => your character will not move when jumping.
You need to save existing X and Z velocity in rb.velocity without any changing them when jumping:
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Vector3 velocity = rb.velocity;
rb.velocity = new Vector3(velocity.x, jumpForce, velocity.z);
}
Since you change velocity instantly - you'll get instant velocity change which is the same as using AddForce
with ForceMode.Impulse