I want to be able to have something to rotate to look at something, but I don’t know how to make it accurate. I only want it to rotate on the Z axis. Any good way I could do this?
You can calculate the direction of the target and zero the z coordinate - this restricts the direction to the XY plane. Then you can calculate a Quaternion.FromToRotation from what you consider your forward direction to the target - if the forward direction of your object is the X axis, for instance, you should use Vector3.right as from direction:
var target: Transform;
...
var atDir = target.position-transform.position;
atDir.z = 0; // restricts direction to the XY plane
transform.rotation = Quaternion.FromToRotation(Vector3.right, atDir);
...
This works prefectly fine, no glitches so far.
void AimAtTarget(Vector2 target, float aimSpeed) {
//getting the angle of the this -> target vector
float targetAngle = Mathf.Atan2(target.y - transform.position.y, target.x - transform.position.x) * Mathf.Rad2Deg;
if (rb.rotation + 90 >= 180) {
rb.rotation = -270;
} else if (rb.rotation + 90 <= -180) {
rb.rotation = 90;
}
//getting the angle between the this -> target and the rigidbody.rotation vector
float diffAngle = targetAngle - (rb.rotation - 90);
if (diffAngle > 180) {
diffAngle -= 360;
} else if (diffAngle < -180) {
diffAngle += 360;
}