How can I keep my z-axis perpendicular to a target location while simultaneously rotating around the x-axis

I would appreciate any help in solving this issue.

Assume up is the y-axis before continuing.

Say I have 2 cubes, A and B. Lets assume B is constantly moving randomly on the (x,z)-plane and A is trying to catch B. Like a cat and a mouse.

A needs to rotate towards B (in other words, A needs to face B) then move towards B. As B is constantly moving A will also have to keep adjusting its rotation to keep facing B.

This can be done with

A.rotation = Quaternion.LookRotation(B.position - A.position);
A.position = Vector3.MoveTowards(A.position, B.position, speed * Time.deltaTime);

This is all fine and good but what if I wanted A to perform some rotating action while chasing B? I can’t because LookRotation changes every rotation axis which would erase any changes I make to As rotation.

For example if I want A to chase B and I also want A to turn towards B while constantly rotating about its x-axis. How could I do this?

Sorry if this is not clear, maybe the following examples will clear things up.

  1. A cat chasing a mouse, the line connecting the cat’s shoulders (or the cat’s z-axis) is always perpendicular to the mouse but the cat’s x-axis changes because the cat is doing front flips while chasing the mouse.

  2. A talking ball with eyes and ears is chasing a different mouse. The line connecting the ball’s ears is always perpendicular to the mouse (i.e. the ball is facing the mouse) but the ball can only move by rolling so its x-axis must change as it follows the mouse.

With these 2 examples hopefully my question, “How can I keep my z-axis perpendicular to a target location while simultaneously rotating around the x-axis,” makes more sense.

Thanks for any help.

Quaternion.LookRotation is very powerful if used right.

The first argument is the axis you always want z to be aligned with, and the other is the direction you want x to try to look toward.

 A.rotation = Quaternion.LookRotation(Vector3.forward, B.position - A.position);

will work just fine.