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

2015/5/28

something wrong on using getOneIntersectingObject

dynamic dynamic

2015/5/28

#
I use getOneIntersectingObject to check any blocked object, once it check a valid object, it get stuck there even other direction cursor key press. Not understand why? Thanks!
    
  public void act() 
    {
        CheckKeyMove();
    } 


public boolean CheckCanMove(java.lang.Class blocker)
    {
        Actor block = getOneIntersectingObject(blocker);
      
        if(block == null)
            return true;
        else
            return false;

    }
    
    public void CheckKeyMove()
    {
        if(Greenfoot.isKeyDown("up"))
        {
           setRotation(270);
           if(CheckCanMove(Brick.class))
              setLocation(getX(),getY()-1);
        }
        else 
        if(Greenfoot.isKeyDown("right"))
        {
            setRotation(0);
           if(CheckCanMove(Brick.class))
              setLocation(getX()+1,getY());        
        } else
        if(Greenfoot.isKeyDown("down"))
        {
            setRotation(90);
           if(CheckCanMove(Brick.class))
              setLocation(getX(),getY()+1);            
        } else
        if(Greenfoot.isKeyDown("left"))
        {
            setRotation(180);
           if(CheckCanMove(Brick.class))
              setLocation(getX()-1,getY());            
        }        
    
    }
The Brick object created in the World class
       for(int i= 0; i< 20; i++)
        {
            brickA[i] = new Brick();
            addObject(brickA[i], locXY[i*2], locXY[i*2+1]);
        }
Super_Hippo Super_Hippo

2015/5/28

#
The 'CheckCanMove' method returns true if the object doesn't intersect with an object of a given class. In your case, you have coded it that the object only moves if it doesn't intersect a brick before it moves. That means if you moving into a brick, you can't escape anymore. You could check the intersecting after it moved and move back if it intersected. This way you won't stuck:
if(Greenfoot.isKeyDown("up"))
{
    setRotation(270);
    setLocation(getX(),getY()-1);
    if(!CheckCanMove(Brick.class)) setLocation(getX(),getY()+1);
}
You need to login to post a reply.