About Archive Tag Cloud Translations RSS

You are writing a comment about Touch Detection in Cocos2d iPhone, here is a quick summary:

A quick look at three different approaches for implementing touch detection using the Cocos2d iPhone library. There are a number of snippets here, and I imagine it would be rather confusing to approach without a basic understanding of ObjC and Cocos2d iPhone.


You are responding to this comment written by Eric Malamisura on June 17th 2009, 23:00.

For those that are having issues sub-classing Sprite I have solved all of the issues.

First off, instead of overriding init, you will need to overwrite the individual methods, for me I am using initWithFile, that is where you will need to call the track method.

Secondly, the rect is not part of Sprite so you will need to create your own rect property. Also as mentioned above the coordinates are slightly wierd so you will need to convert them using the Director.

- (CGRect) rect {
	float w = [self contentSize].width;
	float h = [self contentSize].height;
	CGPoint point = CGPointMake([self position].x - (w/2), [self position].y - (h/2));
	
	return CGRectMake(point.x, point.y, w, h); 
}

Thirdly, if you do not return kEventIgnored and kEventHandled properly some of your clicks may get ignored or missed.

- (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject];
	CGPoint point = [touch locationInView: [touch view]];
	point =  [[Director sharedDirector] convertCoordinate: point];
    
	NSArray *allSprites = [TouchSprite allSprites];
	NSUInteger i, count = [allSprites count];
	
	for (i = 0; i < count; i++) {
		TouchSprite *tSprite = (TouchSprite *)[allSprites  objectAtIndex:i];
		CGRect rect = [tSprite rect];
		NSLog(@"ccTouches Began");
		if(CGRectContainsPoint(rect, point))
		{
			NSLog(@"Sprite Clicked");
			return kEventHandled;
		}
	}
	return kEventIgnored;
}

I have tested this with the ability to drag a sprite across the screen and the coordinate translation I have come up seems to work perfectly. I am still a bit baffled as to why I had to do what I did to get the coordinates to match up, perhaps someone could explain the reason.

Hope this helps someone, took me quit a bit of trial and error to arrive at this solution.


Please be aware that comment forms go stale after one hour.





Comments may make use of LifeFlow MarkDown. Raw html will be escaped.


Quick Introduction to LifeFlow MarkDown Syntax

A highlighted code block:

@@ ruby
def a (b, c):
  b * c
end
@@

Other common languages work as well: scheme, python, java, html, etc.

Other markdown syntax:

 ### This is an h3 title
#### This is an h4 title
**this is bold**
*this is italics*

1. This is an
2. ordered list

* And an unordered
* list too

[this is a link](http://www.lethain.com/ "Lethain")