- Home /
Rotate to look at with physics
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?
Answer by aldonaletto · Sep 11, 2011 at 02:06 AM
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); ...
You have no reason to rotate with physics if you know the end result you're looking for. Physics should be used for unpredictable simulations. The results will be the same, you'd just be wasting CPU cycles using the physics engine.
@PrimeDerektive: Only because you can't think of a reason that does not mean there is none. Even if you know the end result sometimes the route is the goal. For exampe if the object you want to turn can collide with other objects. $$anonymous$$g. a spaceship trying to face a certain direction while being hit be asteroids. Thats a pretty tough problem btw.
@PrimeDerektive: Only because you can't think of a reason that does not mean there is none. Even if you know the end result sometimes the route is the goal. For exampe if the object you want to turn can collide with other objects. $$anonymous$$g. a spaceship trying to face a certain direction while being hit be asteroids. Thats a pretty tough problem btw.
Answer by Crooked97 · Jan 23, 2017 at 02:34 PM
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;
}
You can't use summation operations between quaternion and int. How this work perfectly fine ?
Even though it's not obvious from the answer, this answer is about 2d physics. Rigidbody2D does have a single float value as rotation since it's in 2d space where you can only rotate in the x-y plane.