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

2011/11/26

Java Correction

Steve_888 Steve_888

2011/11/26

#
Below i have provided the section of code i need someone to help with. I'm basically trying to get the robot to move forward but then if a 'wall' is in the way to stop. Only problem is, when it reads it, it ignores the code before the 'if(contactWall..." and so doesn't move at all. If someone knows whats missing please help. Thanks.
public void act()
    {
        if(endItNow()==true)
       {
           Greenfoot.stop();
        }
        else
        {
            int x = getX();
            int y = getY();
            setLocation(x+1,y);
            if(contactWall()==true);
            setLocation(x,y);
        }
    
       
    }
    
 public boolean contactWall()
     {
         Actor wall = getOneObjectAtOffset(0,0,wall.class);
         if(wall !=null) {
         
             return true;
            }
            else {
                return false;
            }
        }
      
kiarocks kiarocks

2011/11/26

#
See if removing the ";" after the if statement helps.
danpost danpost

2011/11/26

#
I think kiarocks is correct and that actually the code is not being ignored, but executing exactly what you told it to do. That is: set x and y to current coordinates and update the location 1 grid (or pixel) right; then if contactWall - DO NOTHING; and finally, reset the location to where it originally was. In all, making it appear to ignore your code.
Steve_888 Steve_888

2011/11/27

#
Ok thanks :) My only other problem now is getting the robot to come back again. What i mean is, i have a robot that is in line with a ball that's the other end of the 'world'. From this code, the robot 'sees' the wall and moves up out the way before carrying on forward. However, how do i make it come back again? Like, go up (to get out the way like it does now), go forward (to clear the object) and then come back down again to its original line? Thanks
Steve_888 Steve_888

2011/11/27

#
.
danpost danpost

2011/11/27

#
You should be able to use the same code (basically). You just need an integer instance variable to control the general direction (1 for left to right (increasing x), and -1 for right to left (decreasing x)). If your robot faces left or right, you can reverse the image (mirrorVertically()) to show it facing the other way.
You need to login to post a reply.