I'm working on a game, and currently I'm trying to make my character not run into walls. I understand how to do it with a Wall class, but I want to use my Ground class as a wall. I can't figure out how to do that though. I can make my character walk on ground, but I can't make it stop if he runs into it. I have two boolean methods, onGround() and inGround(). These methods are used to tell if he's on the ground, so it will walk on the ground, and inGround() is used so I can move him up (when he gets stuck in the ground). It would be easier to have a wall object, but I want to use ground so the character can jump on top of it, and walk, but he won't run inside of Ground.
Here's my onGround() and inGround() methods, and my update() method:
Everything I've tried to fix this problem either glitches him out (as this code currently does) or he just walks through the ground.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public void update() { if (onGround()) { if (jumpTime <= DEF_JUMP_TIME) //Makes it where you can only jump after a few seconds of being on the ground jumpTime++; else jumpTime = 0 ; } while (inGround()) setLocation(getX(), getY() - 1 ); if (timeBetweenFire < DEF_FIRE_TIME) //Makes it where you can only shoot after a few seconds at a time timeBetweenFire++; } /** * Checks if the player is on the ground. * @return true if Player is on the ground */ public boolean onGround() { int height = getImage().getHeight(); Actor ground = getOneObjectAtOffset( 0 , height/ 2 , Ground. class ); return ground != null ; } /** * Checks if the player is in the ground * @return true if Player is in the ground */ public boolean inGround() { Actor ground = getOneIntersectingObject(Ground. class ); return ground != null ; } |