Hi,
I am trying to play a bit around in Unity to make a 2D Tower Defense. I have enemies moving along a path and i want the turret to face enemies in range. I use a list for enemies currently in range of the turret and the turret should face at the direction of the first element in that list. Here is my code for the rotation:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TurnToEnemy : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Transform target = getEnemyInQueue();
if (target != null)
{
Quaternion rotation = Quaternion.LookRotation(target.position - transform.position, transform.TransformDirection(Vector3.up));
rotation.x = 0;
rotation.y = 0;
transform.rotation = rotation;
}
}
Transform getEnemyInQueue()
{
List<Transform> enemyQueue = GetComponent<EnemyQueue>().enemyQueue;
if (enemyQueue.Count != 0)
{
return GetComponent<EnemyQueue>().enemyQueue[0];
}
return null;
}
}
As the turret I have a simple sprite with a circle and a rectangular as cannon. The turret rotates in the direction of one enemy but with either its front (the side the “cannon” is facing to) or its back whatever is nearer to the enemy. The turret should snap and stick to the enemy so a smooth movement is not intended. Can anyone help me with that?