I'm new to game development and I'm trying to create a basic 3D Tower Defence game as my first project. I've created a basic turret in Blender and I'm now trying to rotate 2 different bones to make the turret follow the enemy. The first bone (which I have working) rotates the turret to face the direction of the enemy. The second which I can't get right needs to rotate the gun at the top of the turret to look down at the enemy. I need it to keep facing the same direction as the rest of the turret and don't want it to tilt to either side. So it needs to move on 1 axis only.
I have tried various things, including examples from the Internet but I can't figure it out. So far I've managed to get it to look down at its base, up at the sky and spin like a wheel. Basically everything except where it's supposed to be looking.
Here is the code I have at the moment:
if (enemiesInRange.Count > 0)
{
//Rotate Platform //#### This section works fine
Transform platform = transform.root.Find("Armature/BaseBone/PlatformBone");
Quaternion targetRotation; //Final rotation (I.e. facing the enemy)
Vector3 turretPosition = platform.position; //Store the turrets current position
turretPosition.y = 0; //0 the Y axis to stop the turret tilting up or down
Vector3 targetPosition = enemyManager.activeEnemies[enemiesInRange[0]].transform.position;
targetRotation = Quaternion.LookRotation(targetPosition - turretPosition);
float rotateSpeed = 2.0f * Time.deltaTime;
platform.transform.rotation = Quaternion.Lerp(platform.transform.rotation, targetRotation, rotateSpeed);
//Rotate GunBox //####TO DO: This part is not working
Transform gunBox = transform.root.FindChild("Armature/BaseBone/PlatformBone/LowerArmBone/UpperArmBone/GunBoxBone");
Vector3 gunBoxPosition = gunBox.position;
float angle = Vector3.Angle(gunBoxPosition, targetPosition);
gunBox.RotateAround(gunBox.position, Vector3.left, angle);
Debug.Log(angle);
}
Here's a picture of the turret to give you an idea what I'm working with. You can see in the screenshot that the bone's default X rotation is roughly -50.
Enemies walk through the trench around the turret. The PlatformBone rotates everything from the silver platform upwards.
I also don't understand why the line below makes the turret rotate instead of tilting it. I would expect to rotate the turret around the Y axis to keep it flat on the floor and face another direction. Yet I seem to have to do the opposite (If I select the PlatformBone its Y axis is facing up as expected):
turretPosition.y = 0; //0 the Y axis to stop the turret tilting up or down