views:

64

answers:

2

I seem to be having a strange issue with a 2D game I'm working on. In order to determine if my playable character sprite lands on a platform I first do an if statement checking CGRectIntersectsRect and once I've determined that the player sprite and platform sprite have intersected, I then check to make sure that the center point (plus half the player's height) are above the platform, if it is, I then set the player's 'y' velocity to zero.

playerVelocity.x=5;

playerVelocity.y+=gravity;

if (CGRectIntersectsRect([turtle getBounds], [platform getBounds])) {

 if ([player getPosition].y>p.position.y+([player getBounds].size.height/2)) {
  if (playerVelocity.y>0) {
   playerVelocity.y=0;
   inJump=NO;
  }

 }else {
  inJump=YES;
 }
}

[player setPosition:CGPointMake([player getPosition].x+playerVelocity.x, [player getPosition].y-playerVelocity.y)];

Most of the time this code works over the game cycle, however every now and then, the second "if statement" is disregarded and my player sprite passes through the platform. I'm building this game in OpenGL ES 1.1 with a custom sprite class.

Any insight into this issue would be appreciated!

+1  A: 

One thing to check is to make sure that the Player doesn't really pass through the platform. How tall is the platform? If the platform height isn't much, then the player could be above the platform (in one frame) and then in the next frame (player.y + playerVelocity.y) more than halfway through the platform on the other. Which would mean that it would never "hit" the platform even though it seems visually like it did.

One thing you can do is to print out using an NSLog() the values. this way when you miss, you can check the logs to see what the data values were that missed.

There are many ways to deal with "landing on platforms". One is to make sure that the character has reached a high enough altitude to be "above" the platform, and then if it ever crosses then you reset its location to be on the platform.

christophercotton
+1  A: 

If you're making a platformer, there are a lot of issues like this you're going to have to deal with. Save yourself some headaches and read through the MetaNet tutorials on platformer physics: N tutorials. The issue you mention is addressed in particular, along with several other issues you are likely going to run into.

cc
This looks helpful. Thanks!
Scott