Rotate turret with multiple barrels towards a target and fire
The short version:
I need to rotate a child towards a target, the parent should rotate with it.
The long version:
I have a turret with multiple barrels. Think of it as a ball with multiple cylinders sticking out of it. The cylinders are positioned and rotated arbitrarily.
The cylinders should be selected randomly, the parent rotated towards the target so that the child cylinder faces the target and then the cylinder should fire at the target.
Example image:
I found some helping code here on the forum, but unfortunately that one works only as long as the z axis isn't involved.
This is the code I've come up with so far:
using UnityEngine;
using System.Collections;
public class RotateTowardsTargetAndFire : MonoBehaviour {
[Tooltip("The target towards which to rotate.")]
public Transform target;
[Tooltip("Speed at which to rotate towards target.")]
public float rotateSpeed = 100;
[Tooltip("The list of directions / barrels which will be used.")]
public GameObject[] direction;
// Current direction array index.
private int currentDirectionIndex;
void Start()
{
if( direction.Length == 0)
{
Debug.LogError("Direction mustn't be empty!");
}
NextRandomDirectionIndex();
}
void Update () {
RotateAndFire();
}
/**
* Rotate parent towards target, but using the child for the rotation calculation
* source partially from: http://answers.unity3d.com/questions/715123/rotate-parent-to-aim-child.html
*/
void RotateAndFire()
{
// get current destination
GameObject child = direction[currentDirectionIndex];
// rotate parent towards the direction into which the child faces when it looks at target
Vector3 angles = child.transform.localEulerAngles;
Quaternion m_parentToChild = Quaternion.Euler(-angles.x, -angles.y, -angles.z);
Quaternion lookRotation = Quaternion.LookRotation(target.transform.position - transform.position);
Quaternion finalRotation = lookRotation * m_parentToChild;
transform.rotation = Quaternion.RotateTowards(transform.rotation, finalRotation, rotateSpeed * Time.deltaTime);
// angle to check if we are close enough with the rotation
float angleDiff = Quaternion.Angle(transform.rotation, finalRotation);
// fire bullet and get next direction
if(angleDiff < 0.1f)
{
// debug ray / fire bullet
DebugRay();
NextRandomDirectionIndex();
}
}
/**
* Get the next random direction.
* Ensure that it is different to the current one
*/
private void NextRandomDirectionIndex()
{
// get next index
int nextIndex = Random.Range(0, direction.Length);
// ensure that the next index is different to the current one
if ( currentDirectionIndex == nextIndex)
{
nextIndex++;
}
if( nextIndex >= direction.Length)
{
nextIndex = 0;
}
currentDirectionIndex = nextIndex;
}
private void DebugRay()
{
float length = 5;
float duration = 2;
GameObject child = direction[currentDirectionIndex];
Vector3 forward = child.transform.TransformDirection(Vector3.forward) * length;
Debug.DrawRay(child.transform.position, forward, color, duration);
}
}
As long as I rotate the cylinders in design mode only in X and Y direction, everything is fine, but if I rotate around Z, the calculations are off and the shots, i. e. the debug rays go into the floor and in the sky instead of at the target.
Does anyone know how to solve that problem, i. e. rotate the parent so that the child faces a target and then fire a bullet in the direction of the target?
Thank you very much for the help!
Answer by Roland09 · Jul 15, 2016 at 05:22 PM
Solved it thanks to this and this post. In case someone else needs it, here's the relevant code:
Quaternion relativeRotation;
...
private void NextRandomDirectionIndex()
{
// get next index
int nextIndex = Random.Range(0, direction.Length);
// ensure that the next index is different to the current one
if (currentDirectionIndex == nextIndex)
{
nextIndex++;
}
if (nextIndex >= direction.Length)
{
nextIndex = 0;
}
currentDirectionIndex = nextIndex;
GameObject child = direction[currentDirectionIndex];
relativeRotation = Quaternion.Inverse(transform.rotation) * child.transform.rotation;
}
void RotateAndFire()
{
GameObject child = direction[currentDirectionIndex];
Vector3 targetDir = target.transform.position - child.transform.position;
Quaternion lookRotation = Quaternion.LookRotation(targetDir);
transform.rotation = Quaternion.RotateTowards(transform.rotation, lookRotation * Quaternion.Inverse(relativeRotation), rotateSpeed * Time.deltaTime);
float angleDiff = Quaternion.Angle(child.transform.rotation, lookRotation);
// fire bullet and get next direction
if (angleDiff < 0.1f)
{
// debug ray / fire bullet
DebugRay();
NextRandomDirectionIndex();
}
}
Answer by Crashjumper · Jul 15, 2016 at 03:35 PM
Try messing around with an empty game object at the parent. The turret base model as a child of that. Another empty game object as the child of the first game object. With the two barrels as the child to that game object. The parent will have a horizontal rotate script for the turret base movement. the barrels game object will have a vertical movement script. the rotation ahould use localrotate.
Here is a example layout. Game object Turret base model Horizontal movement script Game object Vertical movement script Barrel Barrel
I will add more when later today once i get home, as i have an example on my pc.
Thanks, an example would be great. I'm confused with horizontal and vertical rotation, the rotation should be in any direction, since the turret is a flying ball with barrels.
Sorry i though the barrels rotated independently. If you are using raycasts or your projectiles are 3x to 5x faster then the target you could use a lerp or slerp lookat
Example http://wiki.unity3d.com/index.php/SmoothLookAt_CS
See if this helps.
Thanks, unfortunately it doesn't solve the problem.
Your answer
Follow this Question
Related Questions
Rotating object relative to player to orient it center of camera regardless of direction. 0 Answers
How can I add rotations to transform.rotation? 0 Answers
Rotation animation worked in Unity 4.6, broke in 5.3.5+ 0 Answers
Object orientation remains the same while rotating object 1 Answer
NavMesh, wait for rotation before moving 0 Answers