Struggling to get the rotation the player is moving in.
Hi, I'm new to Unity and new pretty new to coding. I want the player to rotate in the direction he is moving in for e.g. if he moves left the character should not move side ways the character model should rotate 90 degrees and walk in that direction and then keep looking in that direction. I have not yet implemented the movement, but that's not a problem. I made a script that calculates the angle he is moving in using Unity's input system. The code I made calculates the angle correctly the problem is when you stop pressing the movement buttons the x and z axis goes down of course and then the direction changes then the rotation goes back to either 0°, 90°, -90° or 180°. I thought i could change this by just setting the gravity and sensitivity of the axis to something like 1000, but that didn't work, because if you let one button go 1 frame before you let the other button go the direction still goes back to either 0°, 90°, -90° or 180°. Anyone have any idea how to fix this or maybe another way to calculate the direction please help me. I know I'm bad at explaining things, but hopefully you could understand what I am asking.
My code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class player : MonoBehaviour { public Transform playerBody;
float x;
float z;
float angle;
void Start()
{
angle = 0.0f;
}
void Update()
{
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
if (x != 0.0f && z != 0.0f)
angle = Mathf.Rad2Deg * Mathf.Atan(z / x);
if (z > 0.0f && x == 0.0f)
angle = 0.0f;
else if (z < -0.0f && x == 0.0f)
angle = 180.0f;
else if (x > 0.0f && z == 0.0f)
angle = 90.0f;
else if (x < -0.0f && z == 0.0f)
angle = -90.0f;
else if (x > 0.0f && z > 0.0f)
angle = 90.0f - angle;
else if (x > 0.0f && z < 0.0f)
angle = 90.0f + (angle * -1.0f);
else if (x < 0.0f && z > 0.0f)
angle = (90.0f + angle) * -1.0f;
else if (x < 0.0f && z < 0.0f)
angle = (angle + 90.0f) * -1.0f;
if (x != 0.0f || z != 0.0f)
playerBody.transform.eulerAngles = new Vector3(playerBody.transform.eulerAngles.x, angle, playerBody.transform.eulerAngles.z);
}
}
Answer by mbro514 · Jul 26, 2020 at 12:42 AM
Try this code:
void Update()
{
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(x, 0, z);
if (movement.sqrMagnitude > 0)
{
playerBody.forward = movement.normalized;
}
}