Cocos2d:检测旋转精灵的触摸? [英] Cocos2d: Detect touch on rotated sprite?
问题描述
如何检测旋转的 CCSprite 上的触摸?
How would one detect a touch on a rotated CCSprite?
我熟悉使用 ccTouchesBegan 和 contentSize、anchorPoint 等来让精灵检测触摸是否在其范围内的一般技术......但我不知道一旦精灵被某些人旋转后如何继续角度.
I am familiar with the general technique of using ccTouchesBegan and contentSize, anchorPoint etc. to have a sprite detect if a touch was within its bounds ... but I am not sure how to proceed once the sprite has been rotated by some angle.
我希望精灵本身检测触摸(封装)并通过委托将事件报告给另一个对象.
I want the sprite itself to detect the touch (encapsulation) and report the event via a delegate to another object.
如果有人有一些代码可以分享……那就太好了.
If anyone has some code to share ... would be great.
推荐答案
尝试使用CCNode convertTouchToNodeSpaceAR: 方法将点转换为旋转坐标,然后就可以进行精灵边界的比较了.
Try using the CCNode convertTouchToNodeSpaceAR: method to convert the point to the rotated coordinates and then you can do the compare of the sprite bounds.
我在 CCNode 上将它设为一个类别,因此它可用于任何 CCNode 或子类.
I made this a category on CCNode so it's available to any CCNode or subclass.
@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
和实施:
@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
这篇关于Cocos2d:检测旋转精灵的触摸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!