- Home /
2D Tower Defense: Turret facing enemy
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?
What axis are the turrets rotating on? Are the turret axes aligned or at an angle? Turrets where the axis of rotation does not align with a world axes requires a different solution than one with the they are axes aligned.
Ok problem is solved. The x-axis should turn around the z-axis. Now i used the Quaternion.FromToRotation() method to rotate and it works. Thanks.
Answer by pedronox · Nov 07, 2016 at 07:41 AM
Quaternion rotation = Quaternion.LookRotation(target.position - transform.position, transform.TransformDirection(Vector3.back));
Your answer
Follow this Question
Related Questions
tower defense turret turn right side by 90 degree 0 Answers
How to get turrets to lead enemies : Topdown 2d 1 Answer
Issues with twin cannon script 1 Answer
2D Animation does not start 1 Answer