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

2017/3/4

Move Actor on Other Side of the World

itslit itslit

2017/3/4

#
I'm stumped on how I could make the actor come out from the other side of the world when it touches the edge. I need it to be very swiftly as well. So far it looks like this.
1
2
3
4
if (isAtEdge()) {
            setLocation(600-x,400-y);
        }
           
Super_Hippo Super_Hippo

2017/3/4

#
At the end of your act method:
1
setLocation((getX()+getWorld().getWidth())%getWorld().getWidth(), (getY()+getWorld().getHeight())%getWorld().getHeight());
danpost danpost

2017/3/4

#
Super_Hippo wrote...
At the end of your act method:
1
setLocation((getX()+getWorld().getWidth())%getWorld().getWidth(), (getY()+getWorld().getHeight())%getWorld().getHeight());
That would work only if the world was unbounded (created using 'super(int, int, int, boolean)' with the boolean set to 'false'). If not, then you need to be a little more tricky:
1
2
int x = getX(), y = getY(), w = getWorld().getWidth(), h = getWorld().getHeight();
setLocation((x+(w-3))%(w-2)+1, (y+(h-3))%(h-2)+1);
This will place the actor one off of the edge when transporting (so the actor does not bounce back and forth from edge to edge).
itslit itslit

2017/3/4

#
Thank you so much! That helped a lot. Do you mind explaining the code a little bit?
danpost danpost

2017/3/4

#
The following explains the 'x' part; but, the 'y' part is exactly like it: The code Super_Hippo supplied wraps at -1 and at 600, going to 599 and 0 respectively: ( (x+w)%w, (y+h)%h ) However, we need to wrap at 0 and 599, going to 598 and 1 respectively. By subtracting 1 inside and adding one back outside, we get this: ( ((x-1)+w)%w+1, ((y-1)+h)%h+1 ) This sets the proper lower end for wrapping, but the range is still off by 2 too many, so now we adjust the range (w >> w-2 and h >> h-2): ( ((x-1)+(w-2))%(w-2)+1, ((y-1)+(h-2))%(h-2)+1 } Simplifying, we get this: ( (x+w-3)%(w-2)+1, (y+h-3)%(h-2)+1 ) which is equivalent to what I gave above.
You need to login to post a reply.