简体   繁体   中英

Turning Object towards given co-ordinate

I currently have an object flying though space, I want to make the object turn towards a given co-ordinate.

For some reason the object is spinning round and round instead of adjusting itself.

My trigganometry is almost non-existent and so far I've been using guess work so basic explanation please :-/

public void TurnTowardsDestination(double DestinationX, double DestinationY)
{
    //Current Co-Ordinate of the object.
    double positionX = x; 
    double positionY = y;

            //My failed attempt at understanding atan2.
    float spriteToDestAngle =  (float) Math.toDegrees(Math.atan2((positionX - DestinationX),(positionY - DestinationY)));

            //The Rotate, true is clockwise false anti-clockwise.
    if(spriteToDestAngle > 0.0){
        RotateItem(true);
    }else{
        RotateItem(false);
    }

    Log.w("direction", Integer.toString((int) spriteToDestAngle));
}

Could someone point me to the right tutorial on this or at least explain how I would get the object to move in the right direction.


I used a fix that works: (For anyone else stuck on this) From: http://sinepost.wordpress.com/2012/02/16/theyve-got-atan-you-want-atan2/

    int distX = (int) (DestinationX - x);
    int distY = (int) (DestinationY - y);

    double angleRadians = Math.atan2(distY, distX);
    int angleDegrees = (int)Math.toDegrees(angleRadians);

    //setRotation(angleDegrees);

您可能会发现Line2D.relativeCCW(Point2D)在根据给定向量确定点是顺时针还是逆时针时非常有用。

I would just like to point out that your trig here is actually pretty sound, just your logic is incorrect. For example, if your destination is right above the current position, then the spriteToDestAngle will be 90. Even if you are pointing straight at it, your code states it should rotate. You should store the current direction and compare to that.

EDIT:

To clarify, you never take into account your current direction. You rotate based solely on position.

There's a comprehensive article on this by Neil Brown . Neil is writing in Greenfoot, which is based on Java so it should be quite straight forward to port the example code.

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