So, I have a ‘tank’ enemy in a game I am making in Unity2d. I made a simple script to make the turret part of the tank rotate towards the player. The turret did not face the player correctly, so I put it inside an empty game object I can rotate around so that the turret faces the correct direction, and put the targeting script inside the empty game object. The problem is that no matter which way I rotate it, the turret never faces the player correctly. It will sometimes orient itself correctly but then it turn 180 degrees as soon as the tank starts following the player or until it bumps into any walls. Here is the script, and how I can I get the turret to face the player 100% of the time?
using UnityEngine;
using System.Collections;
public class EnemyTurret : MonoBehaviour {
public Transform target;
void Update () {
if (target != null)
{
Quaternion rotation = Quaternion.LookRotation(target.position - transform.position, transform.TransformDirection(Vector3.up));
rotation.x = 0;
rotation.y = 0;
transform.rotation = rotation;
}
}
}
I also fear it might have something to do with the chassis’ AI follow script as well, so I’m also putting it in if you wanna take a look. Ignore the commented out sections, thats for some multiple target stuff I’m working on.
using UnityEngine;
using System.Collections;
public class TankAI : MonoBehaviour
{
public Transform target;
//public Transform secondTarget;
public float speed = 3f;
public float engageDistance = 3f;
public float ignoreDistance = 10f;
void LookAtTarget()
{
if (target != null)
{
transform.LookAt(target.position);
transform.Rotate(new Vector3(0, -90, 0), Spaaaaaace.Self);
transform.Rotate(new Vector3(speed * Time.deltaTime, 0, 0));
}
/*if (target = null)
{
transform.LookAt(secondTarget.position);
transform.Rotate(new Vector3(0, -90, 0), Spaaaaaace.Self);
transform.Rotate(new Vector3(speed * Time.deltaTime, 0, 0));
}/*/
}
// Update is called once per frame
void Update()
{
if (target != null)
{
if (Vector3.Distance(transform.position, target.position) <= (ignoreDistance))
{
if (Vector3.Distance(transform.position, target.position) > (engageDistance))
{
transform.Translate(new Vector3(speed * Time.deltaTime, 0, 0));
LookAtTarget();
}
}
}
/*if (target = null)
{
if (Vector3.Distance(transform.position, secondTarget.position) <= (ignoreDistance))
{
if (Vector3.Distance(transform.position, secondTarget.position) > (engageDistance))
{
transform.Translate(new Vector3(speed * Time.deltaTime, 0, 0));
LookAtTarget();
}
}
}/*/
}
}
EDIT: I’ve noticed I’m wasn’t entirely clear with what was going on. I’ve rotated the turret object and the sprite so that they SHOULD be rotating to face the player, but they’re facing 180 degrees away from the player some/most of the time, and occasionally rotating correctly.