I'm trying to code a turret to angle towards a target, where I have one part of the turret only rotating on the left/right, and I want to animate another part to only angle up/down. I've got the left/right (RotateTowardsTarget
) working, but I can't get the up/down (AngleTowardsTarget
) to work, it seems to also rotate the object as well as angle it.
turretXRotation
is a child of turretYRotation
. These objects form the top of a gun turret, so the base will rotate, and the gun barrel will angle towards the target
/// <summary>
/// Orient the turret weapon towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void OrientWeaponsTowards(Vector3 lookPosition)
{
RotateTowardsTarget(lookPosition);
AngleTowardsTarget(lookPosition);
}
/// <summary>
/// Rotate towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void RotateTowardsTarget(Vector3 lookPosition)
{
// Determine which direction to rotate towards
Vector3 targetDirection = lookPosition - transform.position;
// The step size is equal to speed times frame time.
float singleStep = weaponRotationSpeed * Time.deltaTime;
// Rotate the forward vector towards the target direction by one step
Vector3 newDirection = Vector3.RotateTowards(
turretYRotation.transform.forward,
targetDirection,
singleStep,
0.0f
);
// Draw a ray pointing at our target in
//Debug.DrawRay(turretYRotation.transform.position, newDirection, Color.red, 3);
newDirection.y = 0;
// Calculate a rotation a step closer to the target and applies rotation to this object
turretYRotation.transform.rotation = Quaternion.LookRotation(newDirection);
}
/// <summary>
/// Angle towards the target.
/// </summary>
/// <param name="lookPosition"></param>
private void AngleTowardsTarget(Vector3 lookPosition)
{
// Determine which direction to rotate towards
Vector3 targetDirection = lookPosition - turretXRotation.transform.position;
// The step size is equal to speed times frame time.
float singleStep = weaponRotationSpeed * Time.deltaTime;
// Rotate the forward vector towards the target direction by one step
Vector3 newDirection = Vector3.RotateTowards(
turretXRotation.transform.forward,
targetDirection,
singleStep,
0.0f
);
// Draw a ray pointing at our target in
//Debug.DrawRay(turretXRotation.transform.position, newDirection, Color.red, 3);
// Calculate a rotation a step closer to the target and applies rotation to this object
turretXRotation.transform.rotation = Quaternion.LookRotation(newDirection);
}
Does anyone know how I can just make the `turretXRotation` only change it's X value to aim towards the target? I've tried similar stuff to the rotating, by zeroing out some of the x/y/z coords, but I can't seem to crack it.