0

I've been playing around with my code trying to make the ball in my program move though to be specific the scenario is a ball maze game where I have to make it so the ball moves 1 square at a time until I reach the goal block at the end however the ball must not move off the maze.

So I wanted to know what do i have to change/add in the following code to make it so my ball can move one space at a time in the directions left,right,up and down with the following code:

public void key(){
        int leftChange=0;
        int rightChange=0; 
        int upChange=0; 
        int downChange=0; 
        if (Greenfoot.isKeyDown("left")){
            if (canMove(leftChange, 0)==true)
            setLocation(getX()+leftChange, getY()) ;
        }
        if (Greenfoot.isKeyDown("right")){
           if (canMove(rightChange, 0)==true)
            setLocation(getX()+rightChange, getY()) ; 
        }
        if (Greenfoot.isKeyDown("up")){
            if (canMove(0, upChange)==true)
            setLocation(getX(), getY()+upChange) ;
        }
        if (Greenfoot.isKeyDown("down")){
            if (canMove(0, downChange)==true)
            setLocation(getX(), getY()+downChange) ;
        }
    }

Again I would appreciate the help very much ^_^.

  • initialize the variables to 1 instead of 0? – JB Nizet Jan 18 '15 at 14:00
  • I tried that just now and nothing happened the ball didn't move even alittle. – KingYoshi HD Jan 18 '15 at 14:03
  • We can't answer such a question, because we have no idea what all these methods do. Use your debugger. – JB Nizet Jan 18 '15 at 14:05
  • Well these are all the methods void act()  Act - do whatever the GoldenBall wants to do.  boolean canMove(int x, int y) (checks if there is a block you can move to and if there is it sets sand to value however if there isn't the value will be set to null.          void key()              void win() – KingYoshi HD Jan 18 '15 at 14:11

1 Answers1

0

If you want to make the ball move one space at a time you need to figure out the height and width of the world and from there find the size of one cell. Then, starting from the cell you want to start at, add or subtract to either the x or y to move you to the next cell.