2d turret problem

Hello,

In my 2d game(player moves along x and y) i have a turret that rotates on z axis (so it’s like a clock); when the player walks under it, the turret follows correctly, but when you get at it’s level (the same height as the turret’s position - so like about 9 o’clock and also 3 o’clock in the right side) it starts to twist (still pointing at the player but also rotates on the x axis)
here is my code:

if (targetT) {

  Vector3 lookDirection = targetT.transform.position - transform.position;

  lookDirection.z = 0;

  Quaternion targetRotation = Quaternion.LookRotation(lookDirection, Vector3.right);

  transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * damp);

//transform.rotation = Quaternion.LookRotation(lookDirection);//works but there is no damp

}

on this line: Quaternion targetRotation = Quaternion.LookRotation(lookDirection, Vector3.right); if i take away the: Vector3.right part the problem remains but it happens on 12 and 6 o’clock; how can i spin this turret correctly all around ? or if there is a way to damp the rotation(last line of code) etc. Thank you for your time

1 Answer

1

Try this:

if (targetT) {
  Vector3 lookDirection = targetT.transform.position - transform.position;
  float angle = mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;
  Quaternion targetRotation = Quaternion.AngleAxis(angle, Vector3.forward);
  transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * damp);
}

This code assumes that ‘forward’ is the right side of your sprite. If it is not, you need to either edit your texture to make it the right side, or modify the angle before doing the AngleAxis() call.

thank you very much, this helps a lot, have to reorient the sprite and other things, but it works; Thanks

it works, have to reorient the sprite and other things, but this helps a lot; Thank you very much !

Please dont' post updates/thank-you notes as another Answer (I converted this one to a comment for you). Instead, click the 'Accept Solution' icon underneath the thumbs next to robertbu's Answer.