0

我正在一个类(路径)中创建一个 CGRect。我已经验证该类正在创建矩形。现在,我在类中构建了一个方法,理论上,当被问及触摸位置是否在矩形内时,它应该返回 true。问题是,它总是返回 false。我已经根据需要验证了该方法是否有效。相关代码如下:

路径.h

#import <Foundation/Foundation.h>
#import "cocos2d.h"

@interface Path : CCSprite {
    CGPoint startP;
    CGPoint endP;
    CGRect pathRect;
    CGPoint touchP;
}

-(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

路径.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

在我的主游戏场景中,我初始化了一个路径并将其添加到一个可变数组中:

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];

然后在 ccTouchesBegan 中,我将触摸位置发送到 touchWithinBounds。但是当矩形被触摸时,它不会报告 true,而是总是报告 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]);

我在各个部分之间是否缺少某种联系,或者我是否误解了交互是如何一起工作的?

谢谢

4

1 回答 1

0

弄清楚了。我的点是我的矩形是错误的。

于 2011-08-13T02:22:53.637 回答