根据我上一个问题中guru的建议,我在我的 init 方法中添加了这段代码,以防止在精灵的透明区域发生触摸事件:
path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, endTouch.x, endTouch.y);
//250(y) is the height of the path, 50(x) is the width
//set your width and height to be the same size as the non-transparent part of your sprite
CGPathAddLineToPoint(path, NULL, 0, 250);
CGPathAddLineToPoint(path, NULL, 50, 0);
CGPathCloseSubpath(path);
然后我像这样修改了我的触摸事件:
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if(gameStat == TRUE)
{
UITouch *touch=[touches anyObject];
CGPoint loc=[touch locationInView:[touch view]];
loc=[[CCDirector sharedDirector] convertToGL:loc];
beginTouch = loc;
for(int i = 0; i < [sprArray count]; i++)
{
CCSprite *sprite = (CCSprite *)[sprArray objectAtIndex:i];
if(CGRectContainsPoint([sprite boundingBox], loc))
{
selectedSprite = sprite;
//test the path
loc = [selectedSprite convertToNodeSpace:loc];
if (CGPathContainsPoint(path, NULL, loc, NO) ) {
NSLog(@"inside");
}
else {
NSLog(@"outside");
}
break;
}
}
}}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint loc1 = [touch previousLocationInView:[touch view]];
CGPoint loc2 = [touch locationInView:[touch view]];
loc2 = [[CCDirector sharedDirector]convertToGL:loc2];
endTouch = location;
int goUp = loc2.y - loc1.y;
if(goUp > 0){
CGPoint locationPath = [selectedSprite convertToNodeSpace:location];
if (CGPathContainsPoint(path, NULL, locationPath, NO) ) {
[selectedSprite setPosition:location];
_spriteTouch = TRUE;
}
}}
现在,这很好用,但我的问题是精灵往往会以错误的方式移动。它应该跟随向上的触摸滑动,但无论我如何向上滑动,它都会继续向右移动。我在这里做错了什么?请帮我。
更新:我设法弄清楚如何修复我的代码,所以这已经解决了。我已经更新了我的代码,以防其他人遇到同样的问题。