I'm creating a CGRect within a class (Path). I've verified that the the class is creating the rectangle. Now, I've built a method into the class that should, in theory, return true when asked if a touch location is within the rectangle. Problem is, it always returns false. I've verified that the method is getting the touch, as needed. Relevant code below:
Path.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface Path : CCSprite {
CGPoint startP;
CGPoint endP;
CGRect pathRect;
CGPoint touchP开发者_如何学Go;
}
-(id)initWithPoints:(CGPoint)sP :(CGPoint)eP;
-(bool)touchWithinBounds:(CGPoint)touch;
@property (nonatomic, assign) CGPoint startP;
@property (nonatomic, assign) CGPoint endP;
@property (nonatomic, assign) CGRect pathRect;
@end
Path.mm
#import "Path.h"
@implementation Path
@synthesize startP;
@synthesize endP;
@synthesize pathRect;
-(id) initWithPoints:(CGPoint)sP :(CGPoint)eP {
if ((self = [super init])) {
startP = sP;
endP = eP;
pathRect = CGRectMake(startP.x-2, endP.y, 5, 480);
}
return self;
}
-(bool)touchWithinBounds:(CGPoint)touch {
touchP = touch;
if(CGRectContainsPoint([self pathRect], touch)) {
return true;
} else {
return false;
}
}
-(void) draw {
glColor4f(1.0f,1.0f,1.0f,1.0f);
glLineWidth(5.0f);
ccDrawLine(startP, endP);
}
-(void) dealloc {
[super dealloc];
}
@end
In my main game scene, I initialize a path and add it to a mutable array:
paths = [[NSMutableArray alloc] init];
Path *path1 = [[[Path alloc] initWithPoints:ccp(winSize.width/3, 0.0) :ccp(winSize.width/3, winSize.height)] autorelease];
[self addChild:path1 z:0];
[paths addObject:path1];
And then in ccTouchesBegan, I send the touch location to touchWithinBounds. But instead of reporting true when the rectangle is touched, it always reports false:
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: [touch locationInView:touch.view ]];
for (Path *path in paths) {
CCLOG(@"%d", [path touchWithinBounds:location]);
Is there some kind of connection I'm missing between the pieces, or am I misunderstanding how the interaction works all-together?
Thanks
Figured it out. I had the points I was originating my rectangle at wrong.
精彩评论