如何检测旋转的CCSprite上的触摸?
我熟悉使用ccTouchesBegan和contentSize,anchorPoint等的一般技术,如果触摸在其范围内,则检测精灵......但是我不确定一旦精灵旋转了一定角度后如何继续.
我希望sprite本身检测触摸(封装)并通过委托将事件报告给另一个对象.
如果有人有一些代码可以分享......会很棒.
尝试使用CCNode convertTouchToNodeSpaceAR:方法将点转换为旋转坐标,然后您可以比较精灵边界.
我在CCNode上将其作为一个类别,因此它可用于任何CCNode或子类.
@interface CCNode (gndUtils)
// Lets a node test to see if a touch is in it.
// Takes into account the scaling/rotation/transforms of all
// the parents in the parent chain.
// Note that rotation of a rectangle doesn't produce a rectangle
// (and we are using a simple rectangle test)
// so this is testing the smallest rectangle that encloses the rotated node.
// This does the converstion to view and then world coordinates
// so if you are testing lots of nodes, do that converstion manually
//
// CGPoint touchLoc = [touch locationInView: [touch view]]; // convert to "View"
// touchLoc = [[CCDirector sharedDirector] convertToGL: touchLoc]; // move to "World"
// and then use worldPointInNode: method instead for efficiency.
- (BOOL) touchInNode: (UITouch *) touch;
// allows a node to test if a world point is in it.
- (BOOL) worldPointInNode: (CGPoint) worldPoint;
@end
Run Code Online (Sandbox Code Playgroud)
和实施:
@implementation CCNode (gndUtils)
- (BOOL) touchInNode: (UITouch *) touch
{
CGPoint touchLoc = [touch locationInView: [touch view]]; // convert to "View coordinates" from "window" presumably
touchLoc = [[CCDirector sharedDirector] convertToGL: touchLoc]; // move to "cocos2d World coordinates"
return [self worldPointInNode: touchLoc];
}
- (BOOL) worldPointInNode: (CGPoint) worldPoint
{
// scale the bounding rect of the node to world coordinates so we can see if the worldPoint is in the node.
CGRect bbox = CGRectMake( 0.0f, 0.0f, self.contentSize.width, self.contentSize.height ); // get bounding box in local
bbox = CGRectApplyAffineTransform(bbox, [self nodeToWorldTransform] ); // convert box to world coordinates, scaling etc.
return CGRectContainsPoint( bbox, worldPoint );
}
@end
Run Code Online (Sandbox Code Playgroud)
@Dad的代码将节点的bbox转换为世界.对于旋转节点,这会扩展bbox,并且对于实际节点之外但在世界bbox内部的触摸,可以返回true.为避免这种情况,将世界点转换为节点的坐标空间,并在那里测试本地点.
| 归档时间: |
|
| 查看次数: |
4593 次 |
| 最近记录: |