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

2019/5/17

Actor Traveling to Predetermined Coordinates

__anna__ __anna__

2019/5/17

#
Hi, I'm making a board game style with already set coordinates as the board spaces. When a question is answered, they go to a space on the board, whether forwards or backwards (the spaces are not set up in a grid). Here is my method within the Actor class: (please let me know if you would like me to post any other pieces of code)
public void moveTo(int pos)
    {   
        int x; int y;
        
        if (position == 0) {x = 100; y = 150;}
        else if (position == 1) {x = 703; y = 107;}
        else if (position == 2) {x = 989; y = 155;}
        else if (position == 3) {x = 1246; y = 114;}
        else if (position == 4) {x = 1161; y = 438;}
        else if (position == 5) {x = 848; y = 351;}
        else if (position == 6) {x = 501; y = 351;}
        else if (position == 7) {x = 189; y = 546;}
        else {x = 771; y = 567;}  //final or win
        
        int distance = (int) Math.sqrt((super.getY() - y) * (super.getY() - y) + (super.getX() - x) * (super.getX() - x));
        turnTowards(x,y);
        move(distance); //create loop
        setRotation(0);
    }
Ideally, I would like to find a way to animate the setLocation() method to see the character traveling between spaces. If this is not possible, what's the workaround? My idea was to find the distance between the two points, make a for loop to move(1), and then set the rotation back to zero. However, because the turn and move axis is not the center, I'm having trouble lining my actor up. Any help would be appreciated, thank you in advance!
danpost danpost

2019/5/17

#
Save the starting coordinates and move from there as you move farther each iteration of the loop. Use Greenfoot.delay(1); within the loop to show the animation:
int speed = 5;
int x0 = getX(), y0 = getY();
for (int i=0; i<1+distance/speed; i++)
{
    setLocation(x0, y0);   
    turnTowards(x, y); 
    move(speed*i+distance%speed);
    setRotation(0);
    Greenfoot.delay(1);    
}
I think I did that right so you can adjust the speed easily. This would replace lines 16 thru 18.
You need to login to post a reply.