Rotating on X and Z axis only

How would I make this -

var rotation = Quaternion.LookRotation(player.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damp);

only rotate the object on the X and Z axis? Thanks!

The simplest thing would be if your two objects are on the same plane.

Barring that, you can at least pretend they are by zeroing out the depth axis before calculating your goal rotation:

var displacement = player.position - transform.position;
displacement.z = player.position.z; //pretend objects are at same height
var rotation = Quaternion.LookRotation(displacement); //ed: thanks to Bunny83

By some clever vector multiplication, you could even make that axis-agnostic, but that’s probably better left for another day.

If you need more control than that, I suppose you could try something like this:

  • Get a rotation from Slerp()
  • Convert that rotation to its vector form using its eulerAngles property
  • Zero out one or more axes
  • Convert that back into a rotation using Quaternion.Euler()

Also remembers that if you’re using rigidbodies, you can set rotation and position constraints locking them on a particular axis, which is sometimes very handy for 2D simulation.

A solution, if the object this applies to has a Rigidbody, is to freeze the rotation on the Y axis under constraints.