I have looked and looked and look for a solution to this issue and not found it, apologies if it does exist and my search skills have just failed, but I really need a resolution!
Background:
I’m building a top down space ship game, I have turrets attached to the players ship (as a child object), I have a sprite renderer attached to the turret and a script that “should” lock the turret to face the direction the ship travels while it is locked.
However I am unable to change to rotation of the turret, it just always points towards the top of the screen.
I have tried adjusting the turrets location rotation, global rotation, forcing it to rotate by 45 degrees, everything I can think of and it just sits there, facing the top of the screen.
Please can some one point me to a tutorial, or post a snippet, or link to documentation that will explain how to achieve what I’m looking to do.
using UnityEngine;
using System.Collections;
public class AlignTurrent : MonoBehaviour
{
// The object that we should be aligned to
public GameObject alignTo;
private Rigidbody2D rb;
void Start () {
rb = alignTo.GetComponent<Rigidbody2D>();
}
void Update ()
{
// Get the direction the object is moving towards
float angle = Mathf.Atan2(rb.velocity.y, rb.velocity.x) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(0, 0, angle);
}
}
I managed to find the issue in the end, I was manually clamping the rotation if the turret to fall inside a min/max rotation range, something in the math for that method is out and was resetting the turrets rotation to “up” in every frame.
Actually it turns out I was still not quite right, the actual solution (for any one else with the same issue) is using the turret.transform.localRotation.
In the end I used the following code to make the turret face the locking position based on the arc of the hard point its attached to.
void Update ()
{
switch(trackState)
{
case TurretTrackState.Locked:
//check if the turret is rotated to the 0 degrees position (if not facing aft)
switch(arc)
{
case DataHandler.Facing.Fore:
case DataHandler.Facing.Port:
case DataHandler.Facing.Starboard:
if(thisTurret.transform.rotation.eulerAngles.z != 0.0f)
{
thisTurret.transform.localEulerAngles = Vector3.Lerp(thisTurret.transform.localEulerAngles,
new Vector3(0.0f, 0.0f, 0.0f),
(turnSpeed * Time.deltaTime));
}
break;
case DataHandler.Facing.Aft:
if(thisTurret.transform.rotation.eulerAngles.y != 180.0f)
{
thisTurret.transform.localEulerAngles = Vector3.Lerp(thisTurret.transform.localEulerAngles,
new Vector3(0.0f, 0.0f, 180.0f),
(turnSpeed * Time.deltaTime));
}
break;
}
break;