在上图中,黄色代表比 iPad 分辨率大的 Sprite 。我想在此处以白色表示的特定位置上允许拖放功能。
我所拥有的是: - CCActor继承CCSprite - targetedBoundingBox是根据sprite的白色圆圈的boundingBox。
我想要的: 如何根据sprite获取touchLocation而不是屏幕?
我的代码:
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
CCActor * newSprite = [self selectSpriteForTouch:touchLocation];
if(newSprite != NULL){
//touchLocation should be according to the sprite.
if (CGRectContainsPoint(newSprite.targetedBoundingBox, touchLocation)) {
[self spriteSelected:newSprite];
return YES;
}
return NO;
}
return NO;
}
最佳答案
最简单的方法是计算你的触摸位置和 Sprite 位置之间的差异,所以你的代码应该如下所示:
首先在你的类中全局定义这个
CCPoint relativePosition;
然后从触摸代码内部计算你的触摸位置和 Sprite 位置之间的差异(只有当触摸实际上在 Sprite 内部时才这样做,这意味着你不会得到 x=-100,y=-999 如果你在 Sprite 外面触摸)
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
CCPoint actorPosition = [actor position];
if (CGRectContainsPoint(actor.targetedBoundingBox, touchLocation)) {
//You now have the touch position here:
relativePosition = ccpSub(touchLocation, actorPosition);
return YES;
}
return NO;
}
代码没有经过测试,只是随手写下的,我敢肯定其中有错误,但它提示了你应该往哪个方向走!,也取决于你在做什么,有更好的方法要处理此问题,请使用 this post举个例子
如果我说的不对,请纠正我:)
关于ios - 检测 Sprite cocos2d 中的特定触摸位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14583203/