Question by
AevinGames · Sep 09, 2015 at 11:07 PM ·
c#
Making a 2D sprite look at another object when instantiated...
Hey, Im making a 2D tower defense game, I made a script that's supposedly meant to make the turret look at the incoming enemy. The problem I have is that it wont look when the enemy has instantiated.
Although when I manually drag & drop the enemy sprite into the inspector slot the turret turns to face the enemy sprite...
No script ive found fixed my problem so please help.
using UnityEngine;
using System.Collections;
public class AISmoothLookAT : MonoBehaviour {
public Transform enemy;
GameObject TheTarget;
public GameObject gunTurret;
void Awake () {
TheTarget = enemy.gameObject;
}
void Update() {
OnRotate ();
}
void OnRotate() {
Vector3 dir = TheTarget.transform.position - this.transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
gunTurret.transform.rotation = Quaternion.Euler(0, 0, angle);
}
}
Comment
Your answer
Follow this Question
Related Questions
Line Renderer for golf game 2 Answers
Has anyone found a way to change Shuriken particles with c# while it is in transit. 1 Answer
How can I reset the score counter? 2 Answers
Object and first-person controller's collision not being registered 1 Answer
OnTriggerStay2D when trigger is spawned on object not moving 1 Answer