Reputation: 216
So I created a turrent model in blender an imported into unity everything was looking good I got a little rotation script put togeather for my hub scene and rotation works good
Now moving into the code trying to rotate the barrel to look torwards the enemy doesnt look so good
Heres a short gameplay video to demonstrate the issue
the barrel of the turrent is facing a completly different place then the enemy I would much prefer to fix the issue in code rather then rebuilding the model from scratch so heres what Im doing currently(thats not working)
private void Update(){
FlameForgedTime.UpdateTime ();
if (isInGame) {
RegenerateHitpoint ();
//Look for enemy
if (FlameForgedTime.Time - lastAttack > StatsHelper.Instance.GetStatValue (Stat.Speed)) {
Collider[] col = Physics.OverlapSphere(transform.position,StatsHelper.Instance.GetStatValue (Stat.Range),LayerMask.GetMask("Enemy"));
if (col.Length != 0) {
//find closest enemy
int closestIndex = 0;
float dist = Vector3.SqrMagnitude (col [closestIndex].transform.position - transform.position);
for (int i = 1; i < col.Length; i++) {
float newDistance = Vector3.SqrMagnitude (col [i].transform.position - transform.position);
if (newDistance < dist) {
dist = newDistance;
closestIndex = i;
}
}
//shoot enemy
//Rotate turrent to look at enemy GameObject.FindGameObjectWithTag("Player").transform.LookAt(col[closestIndex].transform);
ShootEnemy(col[closestIndex].transform);
lastAttack = Time.time;
}
}
}
}
So on my turrent(parent gameobject) i have the tag "Player" as the turrent is loaded in a preloader scene and is not accessible by a public GameObject field
For some reason the Y is the axis the turrent rotates on
Anyways I get the closest enemy to the tower and then do a LookAt to try to get the turret to look at the enemy and then shoot at the enemy however that is not working correctly as you can see by the video
Upvotes: 0
Views: 132
Reputation: 15941
The "forward" axis on your model (that is, the direction the gun barrels point) doesn't line up with what Unity says is the forward axis.
"Forward" in Unity is along the positive Z direction, so your model doesn't line up with its transform's local forward (which is what points towards things when using LookAt()
). Looks like your model is aligned with forward along the positive X axis instead.
There are three ways to fix this:
LookAt()
(not recommended)Upvotes: 2