Basis festgelegt
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class CharacterRotation : MonoBehaviour
|
||||
{
|
||||
[Header("Visual")]
|
||||
[SerializeField]
|
||||
private Transform visual;
|
||||
|
||||
[Header("Rotation")]
|
||||
[SerializeField]
|
||||
private float rotationSpeed = 540f;
|
||||
|
||||
[Tooltip("In welche lokale Richtung zeigt die Grafik standardm??ig?")]
|
||||
[SerializeField]
|
||||
private SpriteForwardDirection spriteForward =
|
||||
SpriteForwardDirection.Up;
|
||||
|
||||
private IMovementDirection movement;
|
||||
|
||||
private enum SpriteForwardDirection
|
||||
{
|
||||
Up,
|
||||
Right
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
movement =
|
||||
GetComponent<IMovementDirection>();
|
||||
|
||||
if (movement == null)
|
||||
{
|
||||
Debug.LogError(
|
||||
"CharacterRotation ben?tigt eine Komponente, " +
|
||||
"die IMovementDirection implementiert.",
|
||||
this
|
||||
);
|
||||
}
|
||||
|
||||
if (visual == null)
|
||||
{
|
||||
Debug.LogError(
|
||||
"CharacterRotation: Kein Visual zugewiesen.",
|
||||
this
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (movement == null || visual == null)
|
||||
return;
|
||||
|
||||
Vector2 direction =
|
||||
movement.MovementDirection;
|
||||
|
||||
// Keine Bewegung -> aktuelle Rotation behalten.
|
||||
if (direction.sqrMagnitude < 0.001f)
|
||||
return;
|
||||
|
||||
RotateTowards(direction);
|
||||
}
|
||||
|
||||
private void RotateTowards(Vector2 direction)
|
||||
{
|
||||
float targetAngle =
|
||||
Mathf.Atan2(
|
||||
direction.y,
|
||||
direction.x
|
||||
) * Mathf.Rad2Deg;
|
||||
|
||||
if (spriteForward ==
|
||||
SpriteForwardDirection.Up)
|
||||
{
|
||||
targetAngle -= 90f;
|
||||
}
|
||||
|
||||
Quaternion targetRotation =
|
||||
Quaternion.Euler(
|
||||
0f,
|
||||
0f,
|
||||
targetAngle
|
||||
);
|
||||
|
||||
visual.rotation =
|
||||
Quaternion.RotateTowards(
|
||||
visual.rotation,
|
||||
targetRotation,
|
||||
rotationSpeed * Time.deltaTime
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user