Question by
AevinGames · Sep 13, 2015 at 06:12 PM ·
c#2dinstantiate
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
Best Answer
Answer by AevinGames · Sep 16, 2015 at 08:53 PM
Solved my own problem, but the script needs to be in an empty gameobject. The console will also spam "TheTarget of AISmoothLookAt" has not been assigned every time you left click. Ignore that.
using UnityEngine;
using System.Collections;
public class AISmoothLookAT : MonoBehaviour {
public Transform TheTarget;
public Transform TheTurret;
public GameObject TurretOB;
public GameObject enemyOB;
private Transform currentBuilding;
private bool hasPlaced;
public Camera Camy;
void Awake () {
}
void Update() {
OnRotate ();
if (currentBuilding != null && !hasPlaced) {
Vector3 m = Input.mousePosition;
Vector3 p= camera.ScreenToWorldPoint(m);
currentBuilding.position = new Vector3(p.x,p.y,0);
if (Input.GetMouseButtonDown(0)) {
hasPlaced = true;
Camy.enabled = true;
}
}
}
void OnRotate() {
if (TheTarget == null) {
return;
}
else{
Vector3 dir = TheTarget.transform.position - TheTurret.transform.position;
float angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
TheTurret.transform.rotation = Quaternion.Euler (0, 0, angle);
}
}
public void Turretbuy () {
hasPlaced = false;
currentBuilding = TheTurret= ((GameObject)Instantiate (TurretOB)).transform;
WoodManager.Woody = WoodManager.Woody - 30;
CoinManager.Coin = CoinManager.Coin - 30;
MetalManager.Metal = MetalManager.Metal - 30;
Cam_Placement.turretN = Cam_Placement.turretN + 1;
}
public void enemyspawn () {
Debug.Log("Base");
hasPlaced = false;
currentBuilding = TheTarget= ((GameObject)Instantiate (enemyOB)).transform;
Camy.enabled = false;
}
}