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

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 detecting 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.

Related

Raycasting Layermask vs RaycastAll

Hi I have a small question on how the raycasting with layermasks work vs using RaycastAll.
I am trying to project my rays from inside my object and layermask the rays to collide with the same layer as the original object, therefore i need to ignore the "hit" on the original object itself.
My question is: when Raycasting uses a layermask does it register a collision with other undesirable layers too and then simply ignore them, or does it not even register a collision with those layers in the first place? Would it be worse or equal on performance if I used RaycastAll to logically decide to respond to a layer or not vs somehow using strictly layermasks? Or is it not even an appreciable difference?
I know some posts say that "if you cast it from inside the object it wont collide with that object" but evidently it does.
Thanks
You can take a look at official Unity's physics preformance tutorial. To start with, Raycast is rather cheap operation but it's performance really depends on how you actually do Raycasting. For example, for one of your questions - RaycastAll is more expensive than doing Raycast on a separate layer, it's also mentioned in the link above. It's based on how actually physics work. Unity doesn't implement physics itself, instead it uses existing solutions (like PhysiX for 3d, and earlier it was Box2d for 2d physics).
Also the length of your ray actually influences Raycast's performance. The shorter ray you cast the better performance you get. The worst case is Raycasting to infinity. Another case is that Collider.Raycast is cheaper than Physics.Raycast.
It's no secret, that there is nothing more that some bunch of math equations behind physics in game development so you may thing in such things - the simplier equation you have, the better performance and time to complete you get. So Raycast can be treated as system of equations where you have the equation of the line (actual Raycast) and some number of equations, which describe some 2d/3d object in plane/space and the task is two calculate the points of intersection between your line (Ray) and other objects.
If you don't have complex physics in your game you may not see the difference between RaycastAll and Raycast with layermask, or shorter ray's length, but performance really differs.

interaction with objects in xna

I'm new to using xna and I want to make my player collide with with multipe walls from the same class. So I looked around and I understood that the best way for doing that is to create a list of variables containing the walls id's and make a loop that circles them all and then returns the variable of the objects that collide.
My question is if there is a faster more efficient way for doing that? I mean if I have like 10000 objects that loop can cause a lot of memory use.
Thx in advance
Option 1) If these 10000 object are walls of a level, then you should probably use some sort of grid (like this very old example: https://en.wikipedia.org/wiki/The_Legend_of_Zelda#mediaviewer/File:Legend_of_Zelda_NES.PNG)
With a grid you only have to check collision with adjacent objects, or only with objects that are nearby.
Option 2) If these 10000 objects are enemies or bullets that move more freely, then you could also calculate the distance first and only check for collision if the objects are nearby.
But may I ask why you are using XNA? I used to work with XNA 4.x but in my understanding it is pretty much dead (http://www.computerandvideogames.com/389018/microsoft-email-confirms-plan-to-cease-xna-support). If you're new to XNA, I would advice to use other software to make games (like Unity3D). In Unity3D the hard part of collision detection is done for you (is has standard functions for collision detection) and Unity3D also works with C# (like XNA)
You always want to do the least amount of processing to get the job done. For a tiled 2D game you usually have a 2 dimensional grid. When the player want to walk on a certain tile you can check that tile if it is allowed to walk there. In this case you just have to check a single tile. If you have a lot of NPC's you could divide your map into sections and keep track of in what sections the NPC's are. Now you just have to do collision detection on the enemies within your section.
When you need expensive collision, pixel perfect or polygon collision you should first check if an object is even close with a simple radius float or BoundingSphere only then you go on with more expensive collision detection.
Same goes for pretty much anything, if you have a 100x100 tilemap but only need to draw 20x10 for the screen then you should just render that portion by calculations. In unreal, mappers create invisible boxes, when inside these boxes it only draws a certain part of the map and only checks collision within these boxes. GameDev is all about tricks to make things work smoothly.

Unity3d - check for collision on non moving objects

I have a sphere build from multiple objects. What I want to do is when I touch/click an object, that object should find all adjunctive objects. But because none off them are moving, no collision detection can be used.
I can't find a way to detect these adjunctive objects even when the colliders do collide with each other, as I can see that in the scene. I tried all the possibilities, but none off them are working, because no objects are moving.
Is there a way to check for manual collision detection, or is there some sort of way to let Unity3d do the collision detection automatically?
You could keep a list of all those objects, then when your event happens you can send messages to all them to do what you want them to do.
Lets assume you want your sphere to break into little pieces. You send a Force message to the sphere. Then you use Newton's Laws of motion and find out how much velocity each piece gets. Remember velocity is a vector thus it has direction.
This is how I would do it and still keep the right amount of control over what happens in my game/simulation. Remember F = ma.
you could use RaycastHit (http://docs.unity3d.com/Documentation/ScriptReference/RaycastHit.html) for your collision, this also works on non-moving objects but it needs more performance
You can add rigidbody to every objects; when you touch one of them, give a force onto it, then it is going to move and trigger event of the adjacent objects.
for the reason you do not want to move the object you touch, you can cancel movement in the OnCollider or OnTrigger event handler function.
I managed to work around this by checking the distance from the selected object and all other objects that are part of the sphere. If the distance is below a certain value, then it is an adjunctive object.
Although this is certaintly not fool proof, it works without problems so far.
I am sorry I was not clear enough. Thanks for all the advice what so ever.

cocos-2d collision detection with a rect and falling objects

I've got a player sprite that I can move around on the screen using the accelerometer. Now I want to check if it collides with any of the many randomly falling objects I've created. I know about the CGRectIntersectsRect function, but I don't want to have to know the other object's name. Is there some kind of getElementAt function like in Java, that I can continue to check if there is any object overlapping with my player?
Thanks in advance!
The only cocos2d equivalent to getElementAt I know of is getChildByTag:. Alternatively You can loop through every child of the layer using:
for (CCNode *child in [self children]) {
if (CGRectIntersects(child.boundingBox, player.boundingBox) {
// perform collision stuff
}
}
Also important to remember is that this is horribly inefficient, particularly with many objects. You might consider using a physics engine to perform the efficient collision detection for you.

Chipmunk objects fall through floor at high velocities. Help?

I'm using Chipmunk cocos2d for what will ultimately be a sound-generation game where colliding particles make noise. But right now, I'm running into a problem: my particles keep falling through the floor!
In the example "bouncing ball" templates, the multiplier on the incoming accelerometer stream is fairly low (around 100.0f) but to get things to really react quickly I am cranking it up:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)accel
{ space->gravity = cpvmult(cpv(accel.x, accel.y), 10000.0f); // originally 100.0f
}
I have found that this can be ameliorated by making dt really small, polling the accelerometer around 1/240 of a second.
Is this the best way? Is there another way to say to Chipmunk "look out, these things move fast"?
In general many physics engines have difficulty with collisions between quickly moving objects that are small relative to their velocities. I do not know the specifics of Chipmunk, but your issue implies that at certain time intervals a check is performed for intersecting objects. If the objects move quickly and are small, it is possible for the time interval where a collision is happening to be skipped.
The two easiest solutions are to use a smaller time interval, or somehow make one of the two objects larger. How are you representing the floor? If you can represent it as a thick rectangle, that should also reduce the problem.
The harder solution is to use a more complicated intersection algorithim, such as using bounding capsules to represent the area of space traversed by a sphere between two samples. If the API does not already support this, it is a pretty hefty amount of math and modification.