I am trying to find collision detection between Two Sprits ( encircle with black color in below picture)
here is the code from which i m trying to find with the help by compairing x cordinate of both sprits but unsuccessful
have a look and tell me what is the mistake
- (void)update:(ccTime)dt {
NSLog(#"Target y %f, player y %f",target.position.y, player.position.y);
if(target.position.y==player.position.y)
// if((target.position.x==player.position.x)&&(target.position.y==player.position.y))
// if((sprite.position.y==player.position.y)||(sprite.position.y==player.position.y))
{
Nslog (#"Matched");
//do Something
}
}
The CCNode class which is the parent of the CCSprite class has a boundingBox property of type CGRect. Using this property of the player and target objects you can check for collisions using...
if (CGRectIntersectsRect(player.boundingBox, target.boundingBox) {
// Kaboom...
}
you could have a look at CGRectIntersectsRect like shown here
http://www.icodeblog.com/2009/02/18/iphone-game-programming-tutorial-part-2-user-interaction-simple-ai-game-logic/
Related
i have a tower and a monster. The tower has a SkShapeNode around it, acting as its range. And i want to check if the monster is still inside the range of the tower( i.e inside the skshape node) every frame.
i have this method which i think checks if there is anything still inside the towers' range:
-(void)update
{
[self.currentScene.physicsWorld enumerateBodiesInRect:self.towerRangeNode.frame usingBlock:^(SKPhysicsBody *body, BOOL *stop) {
if (body == nil) {
[self lostSightOfMonster];
}
}];
}
however, the [self lostSightOfMonster] method never runs.
for additional understanding, i call this method in the update method of the scene:
[self enumerateChildNodesWithName:#"Tower" usingBlock:^(SKNode *node, BOOL *stop) {
Tower *tower = (Tower *) node;
[tower update];
if (tower.hasChosenEnemy) {
[tower updateRotation];
}
}];
}
i suspect its something to do with the enumerating bodies in rect method, however i am not sure.
thanks in advance
I would suggest a different approach. Rather than checking if it is in contact with the sprite I would check its distance to the origin of the tower using Pythagorean theorem. I think the code would be more simple and there would be the added bonus of not having the range sprite to be visible at all times.
here is some concept code to show what I mean:
double distance;
distance = pow(enemySprite.position.x-towerSprite.position.x, 2);
distance += pow(enemySprite.position.y-towerSprite.position.y, 2);
distance = sqrt(distance);
if (distance < towerRange) {
//shoot at ememy
}
You could hypothetically put this in a for loop to check for multiple enemies as well.
Use this code to check for frame intersection of 2 nodes:
if(CGRectIntersectsRect(towerNode.frame, enemyNode.frame))
{
// do your thing
}
If you have more than one tower and one enemy you would use this code:
for(SKNode *towerNode in towerNodeArray)
{
for(SKNode *enemyNode in enemyNodeArray)
{
if(CGRectIntersectsRect(towerNode.frame, enemyNode.frame))
{
// do your thing
}
}
}
The above assumes you are using the physics body of the tower to check for range. Alternately you can also use some simple x and y coordinate checking like this:
if(((towerNode.position.y <= enemyNode.position.y+100) && (towerNode.position.y >= enemyNode.position.y-100)) &&
((towerNode.position.x <= enemyNode.position.x+100) && (towerNode.position.x > enemyNode.position.x+100)))
{
// do your thing
}
In my game, I'm trying to determine what points to dole out depending on where an arrow hits a target. I've got the physics and collisions worked out and I've decided to draw several nested circular SKShapeNodes to represent the different rings of the target.
I'm just having issues working out the logic involved in checking if the contact point coordinates are in one of the circle nodes...
Is it even possible?
The easiest solution specific to Sprite Kit is to use the SKPhysicsWorld method bodyAtPoint:, assuming all of the SKShapeNode also have an appropriate SKPhysicsBody.
For example:
SKPhysicsBody* body = [self.scene.physicsWorld bodyAtPoint:CGPointMake(100, 200)];
if (body != nil)
{
// your cat content here ...
}
If there could be overlapping bodies at the same point you can enumerate them with enumerateBodiesAtPoint:usingBlock:
You can also compare the SKShapeNode's path with your CGPoint.
SKShapeNode node; // let there be your node
CGPoint point; // let there be your point
if (CGPathContainsPoint(node.path, NULL, point, NO)) {
// yepp, that point is inside of that shape
}
I am working on map view app.I want know that how we can identify that coordinates are in my current region(Map region that bound with screen) or outside of it.
Thanks In Advance.
You have different options. You can see this sample code from apple: Regions. That, has I understand, check the device position by the antenna's position.
Or tracking device position, and check if is inside a region defined by You. Check this question
If you find a better solution, please let me know.
EDIT:
To check if a coordinate is visible in the map try using this:
// Your coordinates - Lisbon for example
float lisbonLatitudeValue = 38.7069320;
float lisbonLongitudeValue = -9.1356321;
CLLocationCoordinate2D lisbonCoordinates = CLLocationCoordinate2DMake(lisbonLatitudeValue, lisbonLongitudeValue);
if (MKMapRectContainsPoint(mapView.visibleMapRect, MKMapPointForCoordinate(lisbonCoordinates)))
{
// do something
NSLog(#" - Lisbon is visible");
}
else {
// do something
NSLog(#" - Lisbon is not visible");
}
Hope it helps
I'm new to cocos2d and I made my way through the 'Learning cocos2d' book.
Like in the Book I implemented a scrollingLayer for scrolling, when my gamecharacter moves.
My problem is the following: I'm using a normal Sprite to do the scrolling layer rendering who can I check if my character is touching the scorlling layer?
fyi: It's a fish and he needs to swim through a hole and there are walls above und underneath it and he should not be able to get in front or behind the rocks.
I've searched the internet and this forum, but was not be able to find any suitable solutions.
Is 'Tiled' the kay for happiness, I read about collisions implemented but can't make it out how they are implemented using tmx's
Can someone assist me with that?
For simplier, but powerful collision detection you most likely need physics engine.
I recommend SpaceManager extension for Chipmunk engine.
In Tiled you can add object layer to tmx file, where you can line out all obstacles.
That's how I parse this information in my game scene:
in init:
self.tileMap = [CCTMXTiledMap tiledMapWithTMXFile:#"TileMap.tmx"];
...
smgr = [[SpaceManagerCocos2d alloc] init];
smgr.constantDt = 1/60.0;
smgr.gravity=ccp(0, 0);
[smgr addWindowContainmentWithFriction:0.0 elasticity:0.0 size:CGSizeMake(1000, 1000) inset:cpvzero radius:1.0f]; //borders of your world, can be set from tmx size
player = [smgr addCircleAt:ccp(x,y) mass:6 radius:15];
and somewhere:
- (void) drawWalls {
//searching for object layer called "Collisions"
CCTMXObjectGroup *objects = [_tileMap objectGroupNamed:#"Walls"];
NSMutableDictionary * objPoint;
int x ;
int y ;
int w ;
int h ;
for (objPoint in [objects objects]) {
x = [[objPoint valueForKey:#"x"] intValue];
y = [[objPoint valueForKey:#"y"] intValue];
w = [[objPoint valueForKey:#"width"] intValue];
h = [[objPoint valueForKey:#"height"] intValue];
GameController *controller = [GameController sharedController];
if(controller.retina==1)
{
x=x/2;
y=y/2;
w=w/2;
h=h/2;
}
cpShape *staticShape = [smgr addRectAt:ccp(x+w/2,y+h/2) mass:STATIC_MASS width:w height:h rotation:0];
}
}
Then, you can apply force at "player" object and update your sprite position in "update" method:
playerSprite.position=ccp(player->body->p.x, player->body->p.y);
Of course you can use some other algorithm to detect collision, but this is just an example of storing and retrieving this information from tmx.
I was wondering if anyone could help me with my program,
I have randomised my sprites into a specific set of co-ordinates.
I want one of the sprites that is at that specific co-ordinate, to be able to make them do something when they are at this random co-ordinate. The problem i am having is that i have to make a long list of if statements saying if this sprite is here do this if another sprite is here do the exact same thing.
if (red1.position.y>=0 && red1.position.y<=63) {
id r1animation = [CCMoveTo actionWithDuration:0.2 position:ccp(red1.position.x,33)];
[red1 runAction:r1animation];
}
if (red2.position.y>=0 && red2.position.y<=63) {
id r2animation = [CCMoveTo actionWithDuration:0.2 position:ccp(red2.position.x,33)];
[red2 runAction:r2animation];
}
i want to be able to say if any of the sprites are at that exact co-ordinate then move them to a point, in a short amount of code as possible. so basically grouping the sprites or something i'm not sure.
Thanks
i want to be able to say if any of the sprites are at that exact co-ordinate then move them to a point
Firstly, specify the 'hotspot' programatically:
CGPoint hotspot = ccp(32,32); // convenience macro,
//creates a CGPoint with x = 32, y = 32
You should store a reference to all your sprites in an array when you create them (you can use cocos2d's 'tagging' also, but I usually like to use an array for simplicity)
-(void)init {
//.. misc
// creating sprite returns a reference so keep it in an array
CCSprite* curSprite = [CCSprite spriteWithFile: //...etc]
[self.spriteArray addObject: curSprite];
// add all sprite references to your array
}
Now you can iterate over this array to see if any of the sprite's frames overlap the hotspot:
-(BOOL) checkAllSpritesForCollision
{
for (CCSprite *sp in self.spriteArray)
{
CGRect spriteRect = sp.frame;
if (CGRectContainsPoint(spriteRect,hotspot))
{
// run your action on sp...
}
}
// you might like to return YES if a collision happened?
}
This is a brute force method of checking whether every sprites frame contains a given point. There are many ways to skin this cat of course, but hopefully this will set you on a better path.
What you can do is to calculate the distance:
float pointX = thePoint.position.x;
float pointY = thePoint.position.y;
float pointDeltax = sprite.position.x-pointX;
float pointDeltay = sprite.position.y-pointY;
float pointDist = sqrt(pointDeltax*pointDeltax+pointDeltay*pointDeltay);
But maybe davbryns solution suits your purpose better.