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

2012/5/14

Stopping at walls

TheYoung0ne TheYoung0ne

2012/5/14

#
Hi i am somewhat new at creating games with greenfoot, and i would like to know if anyone can lead me to example code for stopping when i come to a wall that i place into the world. I have a maze type game that i made, but the object that i control just goes right through the wall...Please some one help me with stopping when i come to the wall.
davmac davmac

2012/5/16

#
One easy way to approach this is to check for a collision with the wall after moving, and if there is a collision, restore the original position. The sequence of steps is: 1. Save the current position to some variables (eg originalX, originalY) 2. Move normally 3. Check for collision and if there is a collision: 3a. Restore the location to the saved location There was a recent discussion about this here.
TheYoung0ne TheYoung0ne

2012/5/16

#
So i have this code...
    public void checkCollision()
    {
          Player thePlayer = null;
          thePlayer = (Player)getOneIntersectingObject(Wall_1.class);
          if (thePlayer != null)    
          {    
              getWorld().removeObject(thePlayer);
          }    
    }
I would like when the player runs into the wall the player is removed...but with the code i have now, when i run into the wall, it crashes the program and gives me an error message saying: java.lang.ClassCastException: Wall_1 cannot be cast to Player
SPower SPower

2012/5/16

#
Weird: why do you want to convert a wall into a player object? Just do this:
public void checkCollision()  
{  
      Actor a = getOneIntersectingObject(Wall_1.class);  
      if (a != null)      
      {      
          getWorld().removeObject(this);  
      }      
}
This will remove the object which holds this method (I assume that is a player) when it hits a wall. I make an Actor object, because getOneIntersectingObject will only return an object if it sees a wall object.
TheYoung0ne TheYoung0ne

2012/5/17

#
Ok thanks, that worked...now is there any way i can make the Player re appear?
davmac davmac

2012/5/17

#
What do you mean, re-appear? You could just not remove it...
TheYoung0ne TheYoung0ne

2012/5/18

#
well if i did not remove it wouldn't we just be back in the first place where the player would just go through the wall? I want the player to not go though the wall, but not completely end the game...
danpost danpost

2012/5/18

#
What you need to do is save the coordinate of the player before you moved it. Then move it, and check for collision. If a collision occurred, move the player back to its saved original coordinates (removing it is no neccessary at all).
TheYoung0ne TheYoung0ne

2012/5/18

#
Thanks for all of your help...everything works as intended.
You need to login to post a reply.