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

2016/2/22

Reappear on the other side

khoalabear khoalabear

2016/2/22

#
Hello. When I move my fish, as soon as it reaches the left or right side, I want it to reappear on the other side. I think I need to use isAtEdge() but I'm not entirely sure. Any help is much appreciated
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class User_fish extends Actor
{
    private int movementspeed = 5;
    public void act() 
    {
        checkKeys();
    }    
    
    public void checkKeys()
    {
        if (Greenfoot.isKeyDown("left") )
        {
            moveLeft();
        }
        if (Greenfoot.isKeyDown("Up"))
        {
            moveUp();
        }
        if (Greenfoot.isKeyDown("Down"))
        {
            moveDown();
        }
        if (Greenfoot.isKeyDown("Right"))
        {
            moveRight();
        }
    }
    
    public void moveRight()
    {
            setImage("User_fish-right.png");
            setLocation(getX() + movementspeed, getY());
    }
    
    public void moveUp()
    {
        setLocation(getX(), getY() - movementspeed);
    }
        
    public void moveDown()
    {
        setLocation(getX(), getY() + movementspeed);
    }
        
    public void moveLeft()
    {
        setImage ("User_fish-left.png");
        setLocation(getX() - movementspeed, getY());
    }
}
danpost danpost

2016/2/23

#
Using 'isAtEdge' will only indicate whether the actor is at an edge -- but, it will not indicate which edge the actor is at. Best is probably just getting the x-coordinate before moving and adding the movementspeed value to it; then get the remainder of the new value after dividing by the width of the world. For example, the 'moveLeft' method could be:
public void moveLeft()
{
    setImage("User_fish-left.png");
    int worldWidth = getWorld().getWidth();
    int x = (getX()-movementspeed+worldWidth)%worldWidth;
    setLocation(x, getY());
}
The 'moveRight' method will be mostly the same except for the name of the method, the image filename and line 5, which would be:
int x = (getX()+movement)%worldWidth;
The adding of 'worldWidth' before using the modulus operator in the 'moveLeft' method is to ensure that the operation is not processed on a negative value.
khoalabear khoalabear

2016/2/23

#
Thanks so much
You need to login to post a reply.