Collision detection between layers in Cocos2d? - iphone

I am making a game in Cocos2d. I have enemies that shoot, and have the character shoot. I created a separate layer for the enemies (and their bullets) and a separate layer for the character (and its bullets). The problem is, I don't know how to detect collisions between the two layers. Note, I have the Scene in HelloWorldLayer, and each of the above layers is a child of the scene. Any help is appreciated. Thanks!

You need to add following lines if your using chipmunks
shape->collision_type = kCollisionTypeParticle;
cpSpaceAddCollisionHandler(space_,
kCollisionTypeParticle,
kCollisionTypeParticle,
collisonDetect,
NULL,
NULL,
NULL,
self);
Here collisonDetect is a method we need to register as:
cpBool collisonDetect(cpArbiter *arb, struct cpSpace *space, void *data)
{
<YOUR CLASS> *layer = (<YOUR CLASS> *)data;
[layer collisonDetect:arb];
return cpTrue;
}
Now here here you will handle rest of the code
-(void)collisonDetect:(cpArbiter*)arb
{
NSLog(#"COLLISION DETECTED");
}

You can detect collision in Cocos2D using CGRectIntersectsRect.
Your idea regarding creation of separate layers for enemies and bullets might prove to be confusing. In this scenario you should consider going for one layer. You must have had a look on Ray Wenderlich of collision detection. If not have a look at Simple Cocos2d game.
If you require more help, let me know.

Why not create the bullets on the opposite layer from the bullet source, i.e. layer A is the character and the enemy bullets, layer B is the enemy and the character bullets? Then your collision detection would be on the same layer.

Look into CGRectIntersectsRect.... I haven't done Cocos2D in a LONG time but I do remember using a Scheduler to regularly invoke a method which would detect collisions using the CGRectIntersectsRect method...
I had a limited number of sprites on screen and on every pass of the collision detection method I would check to see if any of my enemy sprite frames intersected with my protagonist's frames using CGRectIntersectsRect.
This is how I did it:
Step 1:
Implement a method that uses CGRectIntersectsRect to check if the the sprite frames are touching. It could look something like:
- (BOOL)detectCollision
{
CGRect frame1 = someframe;
CGRect frame2 = anotherframe;
if(CGRectIntersectsRect(frame1, frame2))
return YES;
else
return NO;
}
Implement a Scheduler to invoke your collision detection method every seconds using:
[self schedule: #selector(detectCollision) interval:0.25];
This way in your game everytime the collisionDetect method is called you can detect collisions. :)

Related

Collision Layer Matrix and Parent/Child object relationships

I come here after some testing, and because after some googling, I was incapable of finding a straight answer.
Suppose I have a player character with a tag set to Player and a layer set to Humanoid. I also have a bunch of NPC performing patrol, wander, and other movement behaviors. Their tags are set to NPC and their layers to Humanoid. Since this is a 2D game using 2D physics, I used the Project Settings collision matrix to make it so that Humanoids do not collide with each other.
In other words, the NPCs and the player characters can pass through each other, while respecting gravity, force, impulse, etc... This is working fine. My problem arises when: I want some child GameObject of NPC which is in layer Default and has a CircleCollider2D of type Trigger and I want to detect that collision in order to perform some actions (e.g.: show dialogue, stop or switch AI Behaviour of the parent object, or others).
From my testing, this seems not to be working, but I might be doing something wrong. So my question is:
If a GameObject A ignores collisions against layer X, will collisions against a GameObject C in layer Y be ignored if C is a child of a GameObject P in layer X?
private void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.CompareTag("Player")) {
Debug.Log("Collided with player");
}
if (!eventConsumed && other.gameObject.CompareTag("Player")) {
var draw = Random.Range(0.001f, 1.0f);
if (draw > 1.0f - eventChance) {
dialogueEvent.Play();
dialogueEvent = null;
}
eventChance = Mathf.Clamp(eventChance * 1.33f, 0.0f, 1.0f);
}
}
In order to detect whether or not a physics collider that is set as a trigger has collided. You would need to use the OnTriggerEnter2D function instead of the OnCollisionEnter2D function.

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.

Free running /side scrolling type game in cocos2d

I want to make free running/side scrolling type game in cocos2d.i try it in tile maps but i am
stucked due to an issue.Issue is i want to jump and after jump the player sprite detects the
lower floor boundary and get the position at floor boundary whenever don't get boundary it
dies.can anyone suggest me what i do or any tutorial etc?Or help me by code example ?
Thanks
I created a basic platformer for the Global Game Jam, using Box2D and adding a couple of classes similar to the Flash engine called "Citrus Engine". You may use this as you like and take it as an example.
http://globalgamejam.org/2012/o
I write code in my game that you want.
So i suggest that you create the player class and set gravity and velocity of player. In update method of player class set the position of the player. And add the floor in array and in update method test the collision between player and floor with CGRectIntersectsRect.
floor *flr = [allfloors objectAtIndex:i];
CGRectIntersectsRect([self boundingbox],[flr boundingbox])
{
self.position = ccp(self.position.x,flr.position.y + flr.contentSize.height/2);
velocity = 0;
}
and whenever you want to jump just apply the Velocity.

Most efficient way to create CCSprites and particles in Cocos2D

Right now, in my game, I am spawning a sprite every second or so at the top of the screen (using a sceduler) using this code:
The init method:
[self schedule:#selector(addMeteor:) interval:1];
The scheduler method:
- (void)addMeteor:(ccTime)dt
{
CCTexture2D *meteor = [[CCTextureCache sharedTextureCache] addImage:#"Frame3.png"];
target = [CCSprite spriteWithTexture:meteor rect:CGRectMake(0, 0, 53, 56)];
//Rest of positioning code was here
}
Doing it this way causes a stutter in the frame rate every second or so (Whenever another sprite is spawned). Is there a way to eliminate that?
Thanks in advance!
Tate
I'm guessing the stutter is more likely coming from other parts of the code. Do you explicitly call removeChild on meteors? That might cause a hiccup, especially with many meteors.
My advice: create N meteor sprites up front. When you need one, make it visible and change its position. When you're done with it, set it to visible = NO to make it disappear.

How to have a character moved around the screen?

I already have a joystick programmed (finally) and I was wondering how I would get a 'hero' to move about the screen based on where the joystick is? I am using Cocos2d and any help would be greatly appreciated!
The simplest way to do this is to subclass CCNode for your player object and then manipulate it as you would any other CCNode. To start with, you can change the player's position struct like so:
player.position = ccp( player.position.x + [joystick xValue],
player.position.y + [joystick yValue]);
This is making some assumptions about how you want your joystick and player to behave, as well as some properties of the joystick class, but hopefully you get my drift. If it isn't clear, [joystick xValue] and [joystick yValue] would be some bounded value (between -1 and 1, say) representing the touch's position on the joystick. Depending on the range of values, you may want to then scale this by some constant to move the player faster or more slowly.
The cocos2d web site has a great tutorial for beginners that I'd highly recommend. You might want to read up on the CCAction class as well for more complicated maneuvers.