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

2011/10/3

I need help with moving.

Darkhex Darkhex

2011/10/3

#
How do i make object to move from left to right? (that it will repeat it) Also to go from up to down.
davmac davmac

2011/10/4

#
What have you got so far? Do you know how to move an object without repeating it?
Duta Duta

2011/10/4

#
Well, here's a very basic way of doing it:
public void moveRight()
{
    int x = (getX() + 5);
    int y = (getY());
    
    setLocation(x, y);
}
public void moveLeft()
{
    int x = (getX() - 5);
    int y = (getY());
    
    setLocation(x, y);
}
public void moveDown()
{
    int x = (getX());
    int y = (getY() + 5);
    
    setLocation(x, y);
}
public void moveUp()
{
    int x = (getX());
    int y = (getY() - 5);
    
    setLocation(x, y);
}
After you have put that code in, you could do something like:
public void moveOnKeyPress()
{
    if(Greenfoot.isKeyDown("left")) {
        moveLeft();
    }
    if(Greenfoot.isKeyDown("right")) {
        moveRight();
    }
    if(Greenfoot.isKeyDown("up")) {
        moveUp();
    }
    if(Greenfoot.isKeyDown("down")) {
        moveDown();
    }
}
And then just place a call to the moveOnKeyPress() method in the act() method. There are better methods, but that's a nice simple one (if a bit lengthy)
You need to login to post a reply.