How to rotate player to face moving direction?
Ok, so the game I'm working on is a 2.5D platformer, you move left and right, and movement is set up to move the character along the local z axis. I have it set up this way because there will be paths that the player can travel along that curve, so I need to be able to rotate the player while they are moving forward to make them turn.
I made several attempts at having the character rotate properly, or use LookAt to make them face the way they are moving, but each time I do it, it messes with the movement. I can move fine in one direction, but if I switch directions the character freaks out and doesn't move properly at all.
void Start()
{
player_rb = GetComponent<Rigidbody>();
col = GetComponent<CapsuleCollider>();
}
void Update()
{
Vector3 fwd = transform.forward * Input.GetAxisRaw("Horizontal") * Speed;
inputVector = new Vector3(fwd.x, player_rb.velocity.y - 2, fwd.z);
transform.LookAt(transform.position + new Vector3(0, 0, fwd.z));
//lookat is what is causing issues
}
void FixedUpdate()
{
player_rb.velocity = inputVector;
}
Answer by disuperguy · Apr 25, 2021 at 12:27 AM
try replacing lines 10-12 with this:
transform.RotateAroundLocal(Vector3.up, Input.GetAxisRaw("Horizontal") * Speed);
inputVector = new Vector3(transform.forward.x, player_rb.velocity.y - 2, transform.forward.z);
//Im not sure if this works but it should look something like this
Doing so makes the character spin around really fast when a movement key is pressed xD
I'm not sure but I had some thoughts on this, and I think it is not working because when the character is rotated, the move direction is change and then it goes back and forth repeatedly.. I'm not sure how to explain it, but I'm wondering if I need to find another kind of solution, like just visually rotating the character, through animation and not mess with the rigid body, idk :x
Answer by ErisArcana · Apr 25, 2021 at 10:36 AM
Well, I got some results, but it kinda confirms what I was thinking, that I should rotate the character with just animation, because if I move back, the character moves backwards and forwards moves in the direction the character is facing.. Idk this is kinda confusing, but with this code I got the character to flip direction.. but now I can only move forward.
Vector3 fwd = transform.forward * Input.GetAxisRaw("Horizontal") * Speed;
inputVector = new Vector3(fwd.x, player_rb.velocity.y - 2, fwd.z);
if (MoveRight == false && Input.GetKeyDown(KeyCode.D))
{
MoveRight = true;
MoveLeft = false;
transform.RotateAroundLocal(Vector3.up, 110);
}
if (MoveLeft == false && Input.GetKeyDown(KeyCode.A))
{
MoveLeft = true;
MoveRight = false;
transform.RotateAroundLocal(Vector3.up, -110);
}
Also for some reason, 180 wasn't actually 180 in game, so I found a number that gave the closest result, and putting in 110 makes the character rotate to -177...