根据我guru的previous question建议,我在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;
}
}}
现在,这很有效,但我的问题是精灵往往会走错路。它应该按照向上滑动的方式进行,但无论我向上滑动,它都会向右移动。我在这做错了什么?请帮帮我。
更新:我设法弄清楚如何修复我的代码,这已经解决了。我已经更新了我的代码,以防万一其他人遇到同样的问题。
答案 0 :(得分:2)
您是否尝试过更改
loc = [selectedSprite convertToNodeSpace:loc];
以下
loc = [selectedSprite convertToWorldSpace:loc];
[编辑:更新样本]
因为对convertToGL的调用:基于点的格式化为OpenGL,其中:
y+ (0,0) |y+
| +------ y+ x- | x+
| | ---- (0,0) ----
| | |
+ ---- x+ | |
(0,0) x+ y-
OpenGl Cocoa Touch Cartesian
来自屏幕的触摸(Cocoa Touch)不了解OpenGL坐标,因此需要使用Cocos2d CCDirector进行转换:
- (CGPoint)convertToGL:(CGPoint)p
将UIKit坐标转换为OpenGL坐标用于将(多)触摸坐标转换为当前布局(纵向或横向)
与
相反
- (CGPoint)convertToUI:(CGPoint)p
将OpenGL坐标转换为UIKit坐标用于将节点转换为用于调用的窗口点,例如glScissor
有时,我得到了混淆和记录(而不是断点),这个点确定了哪个坐标有效,所以我可以找出逻辑。
NSLog(@"%@", NSStringFromCGPoint(touchPoint.position));
答案 1 :(得分:0)
在touchesMoved方法中,您这样做: -
loc2 = [[CCDirector sharedDirector]convertToGL:loc2];
但是没有相应地将loc1转换为GL坐标。我想你应该试试这个: -
loc1 = [[CCDirector sharedDirector]convertToGL:loc1];
这可能会有所帮助。