How to make a 2d player sprite rotate without messing up movement with C#,
Here is the buggy code. When I apply the conditionals that allow the character to rotate, rotation works just fine. However, up and down cause movement up on the y-axis, while left and right cause movement down on the y-axis. x-axis, or horizontal movement, are impossible. Movement is normal when I comment out the if{}else if{} blocks containing transform.eulerAngles = new Vector3(0, 0, rotation); to disable them, so the conclusion is that eulerAngles are doing something to Vector3. Resetting Vector3 to the Input.GetAxisRaw values does not fix the problem.,So when I use the following C# script on my player, I rotate the character but the movement gets jacked up. This is a 2D Sprite to rotate on the z-axis in relation to it's movement direction. It's set to move at 90 and 45 degree angles so it can turn with corners as well:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class player : MonoBehaviour { private BoxCollider2D boxcollider; private Vector3 moveDelta; private Quaternion rotationDelta;
// Start is called before the first frame update
private void Start()
{
boxcollider = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
private void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
//reset moveDelta
moveDelta = new Vector3(x, y, 0);
//Make character move
transform.Translate(moveDelta * Time.deltaTime);
//make player rotate with direction
if (moveDelta.x>0 && moveDelta.y==0)
{
transform.eulerAngles = new Vector3(0, 0, 90);
}
else if (moveDelta.x<0 && moveDelta.y==0)
{
transform.eulerAngles = new Vector3(0, 0, 270);
}
else if (moveDelta.y > 0 && moveDelta.x==0)
{
transform.eulerAngles = new Vector3(0, 0, 180);
}
else if (moveDelta.y < 0 && moveDelta.x==0)
{
transform.eulerAngles = new Vector3(0, 0, 360);
}
else if (moveDelta.y > 0 && moveDelta.x > 0)
{
transform.eulerAngles = new Vector3(0, 0, 135);
}
else if (moveDelta.y > 0 && moveDelta.x < 0)
{
transform.eulerAngles = new Vector3(0, 0, 225);
}
else if (moveDelta.y < 0 && moveDelta.x > 0)
{
transform.eulerAngles = new Vector3(0, 0, 45);
}
else if (moveDelta.y < 0 && moveDelta.x < 0)
{
transform.eulerAngles = new Vector3(0, 0, 315);
}
}
}