简体   繁体   中英

Trying to make a Rigidbody2D face a target using AddTorque

Suppose I have a player-ship and a planet in a 2D unity game. I want to make the ship's rotation fall level relative to the surface directly under it (For example if the part of the surface under the ship is 80 degrees, the ship should tend to fall to 80 degrees while it's over that spot).

I currently have a code that kind-of works:

    Vector2 direction = planet.position - transform.GetChild(0).position;
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg + 90;
    rig[0].AddTorque(-rig[0].rotation + angle);

It does what I want except for the spot where the ship's rotation transitions from 360 to 0 where it does a sudden 360 flip. I'm trying to figure out how to make that not happen.

I don't want to use LookAt() for this because this is supposed to be a torque that tends towards the target direction, not a snap-set to that direction.

A rough work-around I've used in the past is:

Create 2 objects and make them children of your player object.

Position one of them at (-1,0,0) locally and call it LeftObj. Position the other at (1,0,0) and call it RightObj.

Now you can simply check which is closer to target to figure out which is the most efficient way to turn.

float LDist = Vector3.Distance(LeftObj.transform.position, target.transform.position);

float RDist = Vector3.Distance(RightObj.transform.position, target.transform.position);

if (LDist < RDist){

    // Turn left

}else{

    // Turn right

}

Not the most efficient method, but it's simple and quick to set up, and tells you clearly "left or right" regardless of rotation values.

The obvious drawback is that you can't get a rotation value to scale your torque with as you get closer to a target, so you may need to increase the 'angularDrag' on your player Rigidbody to smooth out some stuttering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM