Reputation: 471
Im trying to make a simple FPS player movement with rigid body. The code below works for moving with WASD but for jumping its a bit weird. When pressing space, the character jumps so little and kind of jerks. I'd figure there's something wrong with the Move() function because if I comment that part out, the jumping works fine.
public LayerMask groundMask;
public Transform groundCheck;
public Rigidbody rb;
[Space]
public float speed;
public float jump;
private float x;
private float z;
private void Update()
{
Move();
Jump();
}
void Move()
{
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
Vector3 move = (transform.right * x + transform.forward * z) * speed * Time.deltaTime;
rb.velocity = move;
}
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
rb.AddForce(Vector3.up * jump, ForceMode.Impulse);
}
}
bool IsGrounded()
{
return Physics.CheckSphere(groundCheck.position, 0.1f, groundMask);
}
Upvotes: 0
Views: 345
Reputation: 90639
Well in Move
you hard overwrite the velocity
.
You rather want to keep the Y axis.
Also when dealing with a velocity
this already is a value per second so here you don't want to apply Time.deltaTime
.
void Move()
{
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
var move = (transform.right * x + transform.forward * z) * speed;
move.y = rb.velocity.y;
rb.velocity = move;
}
in general in order to not move faster diagonal I would rather suggest
// This will make sure that the total magnitude of the vector is maximum 1
var input = Vector3.ClampMagnitude(transform.right * x + transform.forward * z, 1f);
move = input * speed;
move.y = rb.velocity.y;
rb.velocity = move;
Upvotes: 1