Cocos2d:检测旋转的sprite上的touch? [英] Cocos2d: Detect touch on rotated sprite?
问题描述
如何检测旋转的CCSprite上的触摸?
How would one detect a touch on a rotated CCSprite?
我熟悉使用ccTouchesBegan和contentSize,anchorPoint等的一般技术有sprite检测如果一个触摸在它的界限...但我不知道如何继续一次sprite已经旋转了一些角度。
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.
我想sprite本身检测触摸(封装),并通过委托向另一个对象报告事件。
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:方法将点转换为旋转后的坐标,然后可以对sprite边界进行比较。
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:检测旋转的sprite上的touch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!