I'm trying to make my first game in Unity and I want a line renderer to draw from the end of a turret's gun barrel. The problem is I'm rotating 2 bones in the turret to make it look at the enemy. I've used the bounding box of the turret to calculate the offset from the turret's origin to the end of the gun barrel. But when the turret rotates this position is obviously wrong. How can I calculate the correct starting point for the line renderer after performing a rotation?
Here is the code for the rotation and the line renderer:
void Start () {
enemyManager = GameObject.Find("EnemyManager").GetComponent<EnemyManager>();
lazerLine = GetComponent<LineRenderer>();
platform = transform.root.Find("Armature/BaseBone/PlatformBone"); //Get the root transform of this turret (I.e. the turret itself, not the gun barrel)
gunBox = transform.root.FindChild("Armature/BaseBone/PlatformBone/LowerArmBone/UpperArmBone/GunBoxBone");
gunBounds = transform.parent.GetComponent<SkinnedMeshRenderer>().bounds.size; //Get the bounding box of the turret
}
void LateUpdate()
{
Vector3 lookAt;
Quaternion platformRotation;
Vector3 gunLookAt;
Quaternion rotation;
if (enemiesInRange.Count > 0)
{
//Rotate Platform (The silver platform at the base of the turret)
lookAt = enemyManager.activeEnemies[enemiesInRange[0]].transform.position - platform.position;
lookAt.y = 0; //0 the Y axis to stop the turret tilting up or down
platformRotation = Quaternion.LookRotation(lookAt);
float rotateSpeed = 10.0f * Time.deltaTime;
platform.rotation = Quaternion.Lerp(platform.rotation, platformRotation, rotateSpeed);
//Rotate GunBox
gunLookAt = enemyManager.activeEnemies[enemiesInRange[0]].transform.position - gunBox.position;
rotation = Quaternion.LookRotation(gunLookAt);
gunBox.rotation = Quaternion.Lerp(gunBox.rotation, rotation, rotateSpeed);
}
if (timer <= effectsDisplayTime)
{
Vector3 lazerStart = transform.position;
//Adjust the lazer to draw from the default position of the top gun barrel (using the bounding box of the turret to calculate the position)
lazerStart.y += (gunBounds.y * 0.85f);
lazerStart.z += (gunBounds.z / 2) + 0.05f;
//Adjust the lazer to follow the current rotation of the gun
/* ##### This is the part I need to add ##### */
//Draw the lazer
lazerLine.enabled = true;
lazerLine.SetPosition(0, lazerStart);
lazerLine.SetPosition(1, enemyManager.activeEnemies[enemiesInRange[0]].transform.position); //Of the enemies in range, shoot the first enemy that entered the turrets range
effectsEnabled = true;
}
}
Here are 2 picture to give you a better idea of what's happening.
This is with the rotation code commented out.
This is with the rotation code running.