user1042757
user1042757

Reputation: 121

how to do collision detection in java

I'm trying to go collusion detection in java for cocos2d for android and heres the code I have

float oldx = player.getPosition().x;
float oldy = player.getPosition().y;
if((player.getPosition().y + player.getContentSize().height > building1.getPosition().y) &&
   (player.getPosition().y < building1.getPosition().y + building1.getContentSize().height) && 
   (player.getPosition().x + player.getContentSize().width > building1.getPosition().x) &&
   (player.getPosition().x < building1.getPosition().x + building1.getContentSize().width))
{
    player.setPosition(CGPoint.ccp(oldx, oldy));
}

but for some reason it doesn't work... why?

Upvotes: 0

Views: 241

Answers (1)

Deco
Deco

Reputation: 3321

You are setting oldx and oldy to player.getPosition().x and player.getPosition().y, respectively. You are using exactly the same checks in your collision detection if-statement so you are essentially setting the position to the same spot it was.

You need to know the position the player wants to move to prior to doing the check that the collision occurs, and then just not allow the player to move there (i.e. don't update their X and Y).

Upvotes: 1

Related Questions