gpt4 book ai didi

cocos2d-iphone - cocos2d : Detect touch on rotated sprite?

转载 作者:行者123 更新时间:2023-12-04 06:43:06 41 4
gpt4 key购买 nike

如何检测旋转的 CCSprite 上的触摸?

我熟悉使用 ccTouchesBegan 和 contentSize、anchorPoint 等来让 Sprite 检测触摸是否在其范围内的一般技术......但是我不确定一旦 Sprite 旋转了某个角度后如何继续。

我希望 Sprite 本身检测触摸(封装)并通过委托(delegate)将事件报告给另一个对象。

如果有人有一些代码要分享......会很棒。

最佳答案

尝试使用 CCNode convertTouchToNodeSpaceAR: 方法将点转换为旋转坐标,然后您可以进行 Sprite 边界的比较。

我在 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

和实现:
@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-iphone - cocos2d : Detect touch on rotated sprite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3273945/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com