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

2022/3/22

Go to a location

AbdulrazaqAS AbdulrazaqAS

2022/3/22

#
Hello, I want my actor to go to a location, I tried the code below but the actor will keep shaking in the location. Please help me.
public void goTo(int x, int y){
        if(getX() != x || getY() != y){
            turnTowards(x, y);
            move(velocity);
        }
    }
Mauckenweg Mauckenweg

2022/3/22

#
Isn´t "setLocation(insertX,insertY)" working?
Mauckenweg Mauckenweg

2022/3/22

#
In the Greenfoot Dokumentation there are premade strings for some actions (e.g "setLocation")
Mauckenweg Mauckenweg

2022/3/22

#
also i think it should work if you just use Line 3 and 4
AbdulrazaqAS AbdulrazaqAS

2022/3/22

#
Mauckenweg wrote...
Isn´t "setLocation(insertX,insertY)" working?
No, it is working but I want the actor to travel there (like physically), not just disappearing and appearing :)
AbdulrazaqAS AbdulrazaqAS

2022/3/22

#
Mauckenweg wrote...
also i think it should work if you just use Line 3 and 4
No, because it will never stop running.
Super_Hippo Super_Hippo

2022/3/22

#
I guess the variable velocity is too high, so it travels over the point back and forth. You could try to set it to the location if it’s closer than the velocity.
public void goTo(int x, int y)
{
    if(getX() != x || getY() != y)
    {
        if (Math.hypot(getX()-x, getY()-y)<=velocity)
        {
            setLocation(x, y);
            setRotation(0); //optional
        }
        else
        {
            turnTowards(x, y);
            move(velocity);
        }
    }
}
Not tested.
AbdulrazaqAS AbdulrazaqAS

2022/3/24

#
Super_Hippo wrote...
I guess the variable velocity is too high, so it travels over the point back and forth. You could try to set it to the location if it’s closer than the velocity.
public void goTo(int x, int y)
{
    if(getX() != x || getY() != y)
    {
        if (Math.hypot(getX()-x, getY()-y)<=velocity)
        {
            setLocation(x, y);
            setRotation(0); //optional
        }
        else
        {
            turnTowards(x, y);
            move(velocity);
        }
    }
}
Not tested.
Thank you, it worked.
You need to login to post a reply.