'After Z-axis Rotation, character (sprite) Flip 180 degrees will not work in a 2d Game
I am developing a 2d side scroller , The player is "swimming" so I was able figure out how to rotate the Z-axis of the sprite + or - depending on Y axis direction of travel If the Y axis is not used the character gradually returns to a Z axis of 0. Since the character can travel left and right, I implemented a Flip() to flip the sprite in the correct direction of travel. Interestingly, The character's sprite will not flip to the correct direction of travel until the Y axis controller is touched again, instead of immediately when the X axis is moved. The character will move in the correct X axis direction however.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControl : MonoBehaviour
{
public Animator animator;
public Rigidbody2D theRB;
private float inputX;
private float inputY;
// Z axis Rotations
private float currentZ = 0.0f;
private float maxZ = 15.0f;
private float minZ = -10.0f;
private float zRotationRate = 0.5f;
private Vector3 rotation;
public float moveSpeed = 7.0f;
public bool facingRight = true;
private void Awake()
{
}
private void Start()
{
rotation = gameObject.transform.rotation.eulerAngles;
}
private void FixedUpdate()
{
// Move character
theRB.velocity = new Vector2(inputX * moveSpeed, inputY * moveSpeed);
currentZ = transform.rotation.z;
RotateZ(inputY);
}
public void Move(InputAction.CallbackContext context)
{
inputX = context.ReadValue<Vector2>().x;
inputY = context.ReadValue<Vector2>().y;
Debug.LogFormat("X Axis: {0} Y Axis: {1} ", inputX, inputY);
if (inputX > 0 && !facingRight)
{
Flip();
}
else if (inputX < 0 && facingRight)
{
Flip();
}
}
private void Flip()
{
facingRight = !facingRight;
//transform.Rotate(0f, 180, 0f);
transform.rotation = Quaternion.Euler(0f, 180, 0f);
}
public void RotateZ(float inputY)
{
if (inputY > 0)
{
rotation.z = Mathf.Clamp(rotation.z + zRotationRate, minZ, maxZ);
transform.rotation = Quaternion.Euler(rotation);
}
if (inputY < 0)
{
rotation.z = Mathf.Clamp(rotation.z - zRotationRate, minZ, maxZ);
transform.rotation = Quaternion.Euler(rotation);
}
if (inputY == 0)
{
if (currentZ < 0)
{
rotation.z = Mathf.Clamp(rotation.z + zRotationRate, minZ, maxZ);
transform.rotation = Quaternion.Euler(rotation);
}
if (currentZ > 0)
{
rotation.z = Mathf.Clamp(rotation.z - zRotationRate, minZ, maxZ);
transform.rotation = Quaternion.Euler(rotation);
}
}
}
}
Thanks for the feedback
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
