旋转精灵来面对一个点(cocos2d)

我似乎有计算我的精灵和触摸点之间的angular度问题。 我试图让我的精灵直接面对触摸点的方向,每当用户触摸屏幕。 这是我的代码:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ CGPoint tapPosition; for (UITouch *touch in touches){ CGPoint location = [touch locationInView:[touch view]]; tapPosition = [self convertToNodeSpace:[[CCDirector sharedDirector] convertToGL:location]]; } float angle = CC_RADIANS_TO_DEGREES(ccpAngle(fish.position, tapPosition)); [fish runAction:[CCRotateTo actionWithDuration:0.5 angle:angle]]; } 

有任何想法吗? 谢谢

将此添加到Nikhil答案的末尾,以避免在触摸位置位于精灵右下angular时出现负angular。

 if (calculatedAngle < 0) { calculatedAngle+=360; } 

试试这个,首先你不需要这个循环,因为你只是最终会碰到最后一个触摸位置。 你可以使用[触及anyObject]如下。

其次,我不确定ccpAngle是怎么做的,但是当这样的macros不起作用的时候,更容易的就是自己去做math。

 -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint tapPosition; UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInView:[touch view]]; tapPosition = [self convertToNodeSpace:[[CCDirector sharedDirector] convertToGL:location]]; float dY = fish.position.y - tapPosition.y; float dX = fish.position.x - tapPosition.x; float offset = dX<0 ? 90.0f : -90.0f; float angle = CC_RADIANS_TO_DEGREES(atan2f(dY, dX)) + offset; [fish runAction:[CCRotateTo actionWithDuration:0.5 angle:angle]]; } 

你可能可以用ccpDiff中的一个点代替dX和dY,但这并不重要。 也取决于你的鱼的头在哪里,你可能需要调整angular度偏移量,但我会留给你。

让我知道这是否有帮助。

CCPoint pos1 = [鱼的位置]; CCPoint pos2 = touchlocation;

 float theta = atan((pos1.y-pos2.y)/(pos1.x-pos2.x)) * 180 * 7 /22; float calculatedAngle; if(pos1.y - pos2.y > 0) { if(pos1.x - pos2.x < 0) { calculatedAngle = (-90-theta); } else if(pos1.x - pos2.x > 0) { calculatedAngle = (90-theta); } } else if(pos1.y - pos2.y < 0) { if(pos1.x - pos2.x < 0) { calculatedAngle = (270-theta); } else if(pos1.x - pos2.x > 0) { calculatedAngle = (90-theta); } } 

在你的运行动作中使用这个calculateAngle ..希望这有助于… 🙂