- Home /
Player rotating towards direction of movement in 3D
So I have a Cube, in my project, and he currently moves and sprints perfectly, but I have tried for hours to make him rotate towards his current direction of movement, but I jus't can't make it happen :(
Here is my code,
private Vector3 moveDirection = Vector3.zero;
public float gravity = 20.0F;
public float speed = 6.0F;
public float sprintSpeed = 8.0F;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded)
{
Move();
Jump();
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
public void Jump()
{
if (Input.GetButton("Jump"))
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= sprintSpeed;
}
}
public void Move()
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
I would appreciate help
also, I think it's a problem with the Vector3, at the top (Vector3.zero) I have no idea so thanksss :)
Answer by Aluminum18 · Apr 08, 2021 at 10:40 AM
well yea but, where and in which part of the script?
Cus I already tried but if I click "a" to move left, he makes a circle to the left, spining infinitely
RotateToward need 3 params, (1) is your current rotation (2) is target rotation (3) is step or rotation speed. You can find your target rotation by passing your moving direction to Quaternion.LookRotation
You may need to use Quaternion.Angle to check your object rotation whether reaches the target rotation for a stopping rotation command.
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
how do i set a rotation for a gameobject (3D) 1 Answer
Checking vector3 gameObject is about to move to (pathfinding collision detection) 1 Answer
Trying to get the camera to orbit, but also steer the player when moving. 0 Answers
How to make an object go the direction it is facing? 6 Answers