How to make certain sprite disappear after touched - Cocos2d - cocos2d-iphone

I want to know how to disappear certain sprite(star) once the MainPlayer touches the Star.
Thanks. By the way, I'm new to Cocos2d and I'm doing it just for fun and educational purpose.
Thanks.

If you want to be able to detect touches in cocos2d, you need to set the isTouchEnabled property to YES in your init method. You can now take advantage of touch events.
Next, create the new method:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//This method gets triggered every time a tap is detected
NSSet *allTouches = [event allTouches]; //Get all the current touches in the event
UITouch *aTouch = [allTouches anyObject]; //Get one of the touches, multitouch is disabled, so there is only always going to be one.
CGPoint pos = [aTouch locationInView:touch.view]; //Get the location of the touch
CGPoint ccPos = [[CCDirector sharedDirector] convertToGL:pos]; //Convert that location to something cocos2d can use
if (CGRectContainsPoint(yourSprite.boundingBox, ccPos)) //Method to check if a rectangle contains a point
{
yourSprite.visible = NO; //Make your sprite invisible
}
}
Other methods that you may want to take advantage of eventually are the following:
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
Hope this helped.

Related

how to properly handle touch events for multiple layers?

I currently have a "Console" CClayer, which is handling touch detection for sprites that have been added to it. However, I also have some sprites that I want to do touch detection on that are not part of the Console layer... They are currently children of a class that inherits from CCNode.
My understanding is, the more cocos objects have the "isTouchEnabled" property set to true, the more performance will be affected, so I am curious how I should approach this?
Should I:
A) Have the console's touchesBegan method perform detection of the sprites belonging to the CCNode?
B) Just implement isTouchEnabled on the CCNode object
C) Some other approach?
well, for starters, you should only concern yourself about performance if you are concerned i.e. you are seeing or measuring (on DEVICES not a simulator) some inappropriate response times.
I would avoid detecting touches that concern another node - it could get messy, software wise. I tend to return YES (from a ccTouchBegan) strictly when the touch is at a location of an object of concern to the detecting node. When you return NO, the dispatcher will pass on the touch to other handlers ('under' the console), until one such CCNode takes the bite. Kind of as follows:
- (void) onEnter{
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
[super onEnter];
}
- (void) onExit{
[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
[super onExit];
}
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
if (!_visible || !_enabled) {
return NO;
}
CGPoint loc = [touch locationInView:touch.view];
loc = [[CCDirector sharedDirector] convertToGL:loc];
if ([self containsPoint:loc]) {
// do your thing here !
return YES;
}
return NO;
}
-(BOOL) containsPoint:(CGPoint) location {
// determine here whether this node should be handling
// this touch.
}

CGRectContainsPoints and bounding box check is off by several pixels

I've been studying this for hours (2 days, actually) and just cannot figure out what is wrong. The touches are accepted and processing, but the isTouchHandled test is triggering TRUE prematurely; as if a different bounding box was touched than the one that is touched. I have several non-overlapping CCSprite buttons, with each pointed to in the levelButtons array. Iterate through to see which one is touched; but it's always the wrong one.
Does the CGRectContainsPoints method get thrown off if these sprites are in their own layer, which is then in another layer? In other words, is CGRectContainsPoints using raw equality of pixel locations as reported by position? If so, a sprite's position relative to the entire screen is different than its reported position if it is a child, which is relative to the parent. Maybe this has something to do with it? My array and the tags of its contents are correctly lining up, I've logged and checked that many times; it appears to be the bounding box check.
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
CCLOG (#"levelButtons size:%i",[self.levelButtons count]);
BOOL isTouchHandled = NO;
for (int i=0;i<25;i++){
CCSprite*temp=(CCSprite*)[self.levelButtons objectAtIndex:i];
CCLOG(#"iteration temp.tag: %i for object: %i",temp.tag,i);
isTouchHandled= CGRectContainsPoint([temp boundingBox], [[CCDirector sharedDirector] convertToGL:[touch locationInView: [touch view]]]);
if (isTouchHandled) {
CCLOG(#"level touched: %i",temp.tag);
break;
}
}
return isTouchHandled;
}
UPDATE: Incidentally, I also just subclassed CCSprite and add the touche methods to the individual sprites in this fashion ,taking my array of sprites out of the picture. The results were the same, so I suspect the CGRectContainsPoints is not properly working when your rect is a child of other children, the coordinates are not being reported correctly, I suspect.
I think it may be problem with an array that you are getting sprites. Any way , this is how i am using the code for getting the sprite tag.
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
for(int i1=0;i1<=25;i1++)
{
CCSprite *sprite1 = (CCSprite *)[self getChildByTag:i1];
if(CGRectContainsPoint([sprite1 boundingBox], location))
{
//Your Code
break;
}
}
I solved this by creating a new CGRect for the CGRectContainsPoint test, and translating the bounding box into the actual onscreen rectangle; the bounding box test will not work on its own if it is located on a child sprite (or layer). It returns its local position only, relative to the parent.

Tiled Map Question in Cocos2d for a Vertical Scrolling Game

I created a tile map using Tiled application. The map is 40X40 with the tileset size of 32X32. In the game the map is scrolling downwards giving the illusion that the car is moving. I am having trouble getting the Y coordinates when I click on the map during the game. I need to convert the Cocos2d coordinate system into a tileset system. When the tile map has reached the end I place the car again at the start of the map. This way the map continues infinitely. Inside the Tiled application I can see the coordinate of the block I need to get which is 3,19 but I am having a hard time figuring out how to convert the Cocos2d coordinate to reflect that tile. Here is my code:
- (CGPoint)tileCoordForPosition:(CGPoint)position {
int x = position.x / self.tiledMap.tileSize.width;
int y1 = ((self.tiledMap.mapSize.height * self.tiledMap.tileSize.height) - position.y) / self.tiledMap.tileSize.height;
return ccp(x, y1);
}
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGPoint tileCoord = [self tileCoordForPosition:location];
}
Check follow link: http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps?s=tmx
Try to get CCTMXLayer object with CCTMXTiledMap's method:
/** return the TMXLayer for the specific layer */
-(CCTMXLayer*) layerNamed:(NSString *)layerName;
Then use one of follow CCTMXLayer's methods:
-(CCSprite*) tileAt:(CGPoint)tileCoordinate;
-(uint32_t) tileGIDAt:(CGPoint)tileCoordinate;
-(uint32_t) tileGIDAt:(CGPoint)pos withFlags:(BOOL) flags;

Detect long touch

I need to detect long touch in the game the game I am trying to make.How can I do so?
Other problem I am facing is to limit simultaneous touches. i.e the sprite won't jump if user touches more than two times immedeatly one after other.
Also is their a way by which I can add touch duration factor to the height of jump the sprite makes?
Thanks
how do you grab your touches? I always use the following methods:
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
- (void)ccTouchMoved:(UITouch *)touchx withEvent:(UIEvent *)event
- (void)ccTouchEnded:(UITouch *)touchx withEvent:(UIEvent *)event
And in these methods you may take total control over all touches. For example remember the time the touch started:
self.startTime = [NSDate date];
for an instance variable startTime, or to check if a touch belongs to a certain object:
CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
This way you can easily implement your touch logic the way you like it...
A good way to do this is - I find - to define all the required variables within the object of the game, like...
#interface Enemy : CCSprite <CCTargetedTouchDelegate> {
EnemyState state;
NSInteger enemyID;
NSDate *startTime;
NSDate *endTime;
UITouch *lastTouch;
ADDED TO SHOW CONCRETE EXAMPLE CODE FOR ccTouchBegan:
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
D_DBG (#"ENEMY ID %i",self.enemyID);
//implement your logic if a touch for this enemy is allowed or not
if (![self.delegate touchIsAllowed: enemyID touch: touch]) return NO;
//if the enemy is untouched, then may be touched
if ((state == kEnemyStateUngrabbed) && (![self containsTouchLocation:touch] )) return NO;
state = kEnemyStateGrabbed;
self.startTime = [NSDate date];
[self.delegate informAboutEnemyStarted: self.enemyID startTime: self.startTime atPoint: self.position];
return YES;
}

Dragging a particularly large sprite up and down like scroll effect in COCOS2D

I am really stuck on this. My application is in landscape view and on one screen i wanted my instructions image to be scrollable. I have added this image as a sprite. First i tried to get scroll effect available from other sites, but soon i saw that scrolling was being done for the complete screen and not the sprite image. Then i resorted to implement the scrolling effect by dragging the sprite only in y axis (up and down). Unfortunately i am messing things somewhere, due to which only a portion of the sprite (shown on the screen only with the height 320pixels) is being dragged and the rest of the sprite is not being shown. The code is as follows
in the init layer function i have
//Add the instructions image
instructionsImage = [Sprite spriteWithFile:#"bkg_InstructionScroll.png"];
instructionsImage.anchorPoint = CGPointZero;
[self addChild:instructionsImage z:5];
instructionsImage.position = ccp(40,-580);
oldPoint = CGPointMake(0,0);
self.isTouchEnabled = YES;
//The touch functions are as follows
- (BOOL)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
// Move me!
if(touch && instructionsImage != nil) {
CGPoint location = [touch locationInView: [touch view]];
CGPoint convertedPoint = [[Director sharedDirector] convertCoordinate:location];
CGPoint newPoint = CGPointMake(40, (instructionsImage.anchorPoint.y+ (convertedPoint.y - oldPoint.y)));
instructionsImage.position = newPoint;
return kEventHandled;
}
return kEventIgnored;
}
//The other function
- (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
// Move me!
if(touch && instructionsImage != nil) {
CGPoint location = [touch locationInView: [touch view]];
CGPoint convertedPoint = [[Director sharedDirector] convertCoordinate:location];
oldPoint = convertedPoint;
return kEventHandled;
}
return kEventIgnored;
}
Your approach is generally correct.
The code did not format properly, and you were not clear on exactly what the symptom is of the problem...
But it appears as if your math in the ccTouchesMoved is wrong. The anchor point is not what you care about there, as that's just a ratio within the image where the position and rotation anchor occurs. Set that, like you do, to whatever makes sense in the constructor but after that you don't need to reference it.
Try just adding your movement to the sprite:
deltaY = convertedPoint.y - oldPoint.y;
Now you know how many pixels your finger has moved up and down.
Reset your oldPoint data for next time:
oldPoint.y = convertedPoint.y;
Now apply this delta to your sprite:
instrucitonsImage.position = ccp(instructionsImage.position.y,instructionsImage.position.y + delta);
Should do it.