- Home /
Get instantiated prefab position from Collision Trigger
So, I made a sprite which have implemented a pathfinding. I have a turret which rotates to that sprite and shoots.
The turret rotates correctly only if the sprite is a GameObject. But there is the problem, i need that sprite as a prefab.
So the rotation script needs both target position and turret position. The prefab is being instantiated in the game, so i changed the turret rotation script to get the INSTANTIATED prefab position by checking the current GameObject collision (a instantiated prefab is becoming a GameObject, right?)
Here is a visual with what i'm talking about (or just see scripts below): https://www.youtube.com/watch?v=4vWc4EQiAf8&feature=youtu.be (in first phase i'm showing how the turret rotates corectly with sprite being a gameobject and after that, i made it a prefab and there we go...)
Rotation script:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
inVision = true;
debug = collision.transform.localPosition.ToString() + collision.name;
Vector3 vectorToTarget = collision.transform.localPosition - transform.position;
float Angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(Angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * RotationSpeed);
}
}
Solved: Actually localPosition is something else than in-game position so it had to be converted https://docs.unity3d.com/ScriptReference/Transform.TransformDirection.html
So the script looks like: private void OnTriggerStay2D(Collider2D collision) { if (collision.gameObject.CompareTag("Enemy")) { inVision = true;
vectorToTarget = collision.transform.TransformDirection(collision.transform.localPosition) - transform.position;
float Angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(Angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * RotationSpeed);
}
}
Notes: i switched to OnTriggerStay2D because OnTriggerEnter2D is doing just that,it tells if he enters, one single loop. So to avoid creating other variables to store the transform and getting localposition in a loop, better switch to that function.