# How to calculate a direction that will turn a parent so that a locally-rotated child is faced in a given direction?

Imagine an old sailing ship with cannons: they're pointed out at 90° angles from the ship's hull, so in order to fire them, you have to turn the whole ship so that the cannons are pointed at the target. I'm hoping to figure how to calculate "where to point the ship so that the cannons are aimed correctly," but for any possible cannon-angle (not just 90°) in 3D space.

I'm an experienced dev but a total 3D newb, so this vector stuff is wrinkling my brain. This is what I have right now, calculated from the child's (cannon's) gameObject:

Vector3 directionToAim = (transform.localRotation * (transform.position - target.position)).normalized;

It's working for side-facing weapons (like the sailing ship), but for forward-facing weapons it turns the parent in the opposite direction, directly away from the target. If I invert it to (target.position - transform.position) the forward-facing weapons work fine, but the side-facing weapons face the opposite way.

Also, my vague understanding is that it's better to use Quaternions for this, rather than Vector3, is that right? Can someone help me grasp how these parent/child rotations can be calculated?

Your answer leaves out the step of actually applying the direction-to-aim to the parent. Depending on how you use directionToAim, the parent (ship) might roll (stop being upright).

A slightly simpler solution, which is immune to roll in most cases:

//Get the rotation we would apply to the child to make it look at the target
Quaternion rotation = Quaternion.LookRotation(target.position - child.position, Vector3.up);
//Apply this rotation to the parent's rotation (rotate the parent so that the child faces the target)
parent.rotation = rotation * Quaternion.Inverse(child.localRotation);


Apparently I needed to invert the quaternion localRotation. The final answer looks like this:

Vector3 targetDirection = (target.position - transform.position).normalized;
Vector3 directionToAim = Quaternion.Inverse(transform.localRotation) * targetDirection;


Hope it helps anyone else wrestling with this!

• Rotations in 3d are not commutative. Order of operation matters Jul 3, 2020 at 4:17

You can first determine the direction of the aim.

Vector3 mainDirection = ship.transform.position - aim.position;

Then you can calculate the angle between cannons vector and the mainDirection vector. And this will be the angle that ship should be rotated in order to make cannons point in the correct direction.