This site requires JavaScript, please enable it in your browser!
Greenfoot back
tobias1798
tobias1798 wrote ...

2014/4/22

Movin to a Target in ONE Straight Line.

tobias1798 tobias1798

2014/4/22

#
So I want a Spacecraft to move to a Target-Position, but it always goes far off the course.
    public void moveToTarget(double targetX,double targetY)
    {
        //Position of the Craft
        double craftX;
        craftX = getX();
        
        double craftY;
        craftY = getY();
        
        //Calculation of the Distance in X- and Y-Direction
        double distX;
        distX = targetX - craftX;
        
        double distY;
        distY = targetY - craftY;
        
        //Distance between Craft and Target
        double distTargetDouble;
        distTargetDouble = Math.sqrt((distY * distY) + (distX * distX));
        int distTarget = (int) distTargetDouble / 2;
        
        //Calculation of Angle
        
        double turnRadiusDouble;
        turnRadiusDouble = Math.toDegrees(Math.atan(distY / distX));
        int turnRadius = (int) turnRadiusDouble;
        
        //Movement
        
             //Turning
            
            turn(turnRadius);
            
            //Moving
            int i=0;
            while (i < distTarget) {   
             move(2);      
             i++;     
            }
    }
Here's my Code, so if anyone has got an idea whats going wrong, please help me
danpost danpost

2014/4/22

#
Take a look at my Radial Graphs scenario. It will show you the possible direction (angles of movement) that are possible with different speeds of your actor using 'move'. To move in a straight line, you would either have to track the location of the actor using 'double' values (like the SmoothMover class does) or you can hold the initial location coordinates in fields and use a counter to move the new distance from the original location, with code similar to the following:
// instance fields
int xOrigin, yOrigin, xDestination, yDestination, lastDistance;
// movement code
if (getX() != xDestination || getY() != yDestination) // if not at destination
{
    int distToGo = (int)Math.hypot(getX()-xDestination, getY()-yDestination); // how close
    if (distToGo <= 2) setLocation(xDestination, yDestination); // if within range, go there
    else
    {
        setLocation(xOrigin, yOrigin); // go back to origin
        move(lastDistance += 2); // move a bit further toward destination
    }
}
To start the movement:
xOrigin = getX(); // save starting x
yOrigin = getY(); // save starting y
xDestination = /** whatever */; // save ending x
yDestination = /** whatever */; // save ending y
lastDistance = 0; // reset distance moved
You need to login to post a reply.