- Home /
Question by
klaermans32 · Jul 02, 2020 at 11:12 AM ·
movementrigidbodyvelocitymovetowards
How do i add velocity in direction depending on WASD keys pressed
I haven't found any topic about such a simple thing with a working solution so here I'll clarify. I have a 3D character, that aims at mouse like in an FPS game. I just want to add velocity to the rigidbody in it's forward direction when W is pressed, in it's right direction when D is pressed, in a 45 degree angle when W and D are pressed at the same time and so on. I hope someone can link me something that works or say what is missing in my code:
//Get WASD input
Vector2 movementInput = controls.Player.Movement.ReadValue<Vector2>().normalized;
Vector3 direction = transform.forward;
//The following 2 lines work for walking forwards and backwards relative to aiming direction
direction.x *= movementInput.y;
direction.z *= movementInput.y;
//Now i need to have left and right (it should also go diagonal is forwards and right is pressed for example)
Vector3 finalVelocity = rigidBody.velocity + direction * movementSpeed * Time.deltaTime;
rigidBody.velocity = finalVelocity;
Comment
Answer by rh_galaxy · Jul 02, 2020 at 10:06 PM
You are very close, I think you should experiment with this
direction.x *= movementInput.x;
direction.z *= movementInput.y;
It's all about getting the direction vector correct from the movement x and y.