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

2021/1/16

Barrier

Sathya_srikanth Sathya_srikanth

2021/1/16

#
Im trying to make this object stop moving if it touches the object "d", and i have been unsuccessful...can anyone pls help me? this is the code of the moving object.
public class Log2 extends Actor
{
    public boolean moveX = false; 
    
    
    public void moveLeft()
    {  setLocation(getX()-5, getY());
         
     }
     public void stop()
     { move(0);}
     public void moveRight()
     {setLocation(getX()+5, getY()); }
    public void act() 
    {
        
        if(Greenfoot.isKeyDown("LEFT")) 
            moveLeft();
            else if(Greenfoot.isKeyDown("LEFT") || (isTouching(d.class)))
            moveX = !moveX;  stop();                 
          
         if(Greenfoot.isKeyDown("RIGHT")) 
          moveRight();
        
        
    }    
danpost danpost

2021/1/16

#
Remove lines 11 and 12 (a method that does nothing is a useless method). Replace lines 19 and 20 with:
Super_Hippo Super_Hippo

2021/1/16

#
Line 20:
moveX = !moveX;  stop();
Without using {}, only everything until the first ; is inside the “else if” there so the “stop”-method is executed regardless. Line 19:
else if(Greenfoot.isKeyDown("LEFT") || (isTouching(d.class)))
This will always be true because the first condition has to be met to reach that line (line 17 is the same thing). Line 11:
move(0);
That method is not doing anything. You are moving left (line 18 → 7) and then you don’t move (line 20). So in total, you moved left. What you need to do is: move and then if there is an obstacle, move back to where you were coming from. move(0) is the same as doing “setLocation(getX(), getY())” which obviously doesn’t have any effect.
danpost danpost

2021/1/16

#
REPOSTING: Remove lines 11 and 12 (a method that does nothing is a useless method). Replace lines 19 and 20 with:
if (isTouching(d.class)) moveRight();
You need to login to post a reply.