I am trying to create a turret which rotates to face a target. The base rotates left and right, while the head rotates up and down.
I have successfuly made the base only rotate around the y axis, but the problem I am having is making the head only rotate on it’s x axis - it just doesn’t work right. (Shown here)
This is the code I have for the turret:
using UnityEngine;
using System.Collections;
public class Turret : MonoBehaviour
{
public Transform target;
public Transform rotateTransform;
private Vector3 initialRotation;
public Transform pivotTransform;
private Vector3 initialPivot;
public float rotateSpeed = 0.25f;
void Start()
{
initialRotation = rotateTransform.eulerAngles;
initialPivot = pivotTransform.eulerAngles;
}
void Update()
{
if (target)
{
RotateTowards(target.position);
}
}
void RotateTowards(Vector3 position)
{
Vector3 direction = position - transform.position;
if (rotateTransform)
{
rotateTransform.rotation = Quaternion.Lerp(rotateTransform.rotation, Quaternion.LookRotation(direction), rotateSpeed);
rotateTransform.eulerAngles = new Vector3(0, rotateTransform.eulerAngles.y, 0) + initialRotation;
}
**///The problem area////**
if (pivotTransform)
{
pivotTransform.rotation = Quaternion.Lerp(pivotTransform.rotation, Quaternion.LookRotation(direction), rotateSpeed);
pivotTransform.eulerAngles = new Vector3(pivotTransform.eulerAngles.x, 0, 0);
}
}
}