开发者

iPhone OpenGL ES: Firing a bullet and detecting if it hit an object

开发者 https://www.devze.com 2023-02-01 02:48 出处:网络
I have worked out how to detect touching on an object using glReadPixels but how would I detect if a object hits another object (a bullet for example).

I have worked out how to detect touching on an object using glReadPixels but how would I detect if a object hits another object (a bullet for example).

I cant do that with detec开发者_如何学Pythonting colours.


As others have said, do this in the object model, not in the graphics.

For one simple model, give each object other than a bullet a size. Then check if a bullet's location is within that object's radius every tick. In pseudocode:

for each bullet
  for each hittableObjectInWorld
    if ([hittableObject isTouchedBy:bullet]) {/*handle collision*/}
  endFor
endFor

hittableObject::isTouchedBy:(Sprite *)otherObject {
  xDistance = [self x] - otherObject.x;
  yDistance = [self y] - otherObject.y;
  totalDistance = sqrt((xDistance*xDistance) + (yDistance*yDistance));
  if (totalDistance <= [self size]) return YES;
  else return NO;
}

Now you've got a simple collision detection system. There are some abstractions here: We treat every hittable object as if it were shaped like a sphere with its 'size' as its radius. Bullets are pinpoint small, but you can correct for that by adding a bullet's radius to the radius of each of the hittable objects and it makes the math run a wee bit faster this way.

This might be the simplest possible collision detection system. There's a lot of room for improvement here. The big thing is you're doing the number of bullets times the number of hittable objects checks each tick. If you have many bullets and many objects in the world, that can be a lot of processor time. There's all sorts of hacks to cut down on the number of checks you have to do. If you run into speed problems with this version, that's the next thing to start tuning up.

Good luck!


You do it in your object model, not in your graphics code. OpenGL is only tangentially related to collision detection.


OpenGL only deals with the graphical display of your game's objects. Any logic about how the objects in your game behave should be done in the code that manages the state of the objects not in the OpenGL graphics code.

What you are looking for is collision detection which can be a fairly deep topic. Just to be clear, once you detect a collision (e.g. a bullet hitting an object) you will more than likely run some OpenGL code to display the reaction of the collision to the user but the actual detection of the collision should not occur within the OpenGL realm.

Lastly, if you find all of this a bit overwhelming I would recommend the use of a game engine like cocos2d or Unity.

0

精彩评论

暂无评论...
验证码 换一张
取 消