我的 sprite 套件游戏中有一个图标,我打算将其用作一个角色射击另一个角色时的动画射弹。我正在尝试调整这个射弹的方向以指向目标。
我将它旋转 pi/4.0 的底角,使其指向右侧。然后我希望箭头从这个位置旋转并指向目标。
下面的代码几乎可以工作,但在我看来,抛射物似乎总是偏离正确的角度。如果角度正确,当箭头被赋予移动到目标x,y坐标的 Action 时,箭头将指向移动的方向。
如何正确计算从一个 (x,y) 点到另一个 (x,y) 点发射射弹的角度?
编辑:下面的代码现在可以工作了,只需要执行 zeroCheckedY/zeroCheckedX。
//correct for pointing in the bottom right corner
float baseRotation = M_PI/4.0;
float zeroCheckedY = destination.y - origin.y;
float zeroCheckedX = destination.x - origin.x;
SKAction* rotate = nil;
if(zeroCheckedX != 0)
{
//not sure if I'm calculating this angle correctly.
float angle = atanf(zeroCheckedY/zeroCheckedX);
rotate = [SKAction rotateByAngle:baseRotation + angle duration:0];
}else
{
rotate = [SKAction rotateByAngle:baseRotation duration:0];
}
最佳答案
我有一个类似的问题:大炮必须“跟踪”一个目标。
在 CannonNode
中,我定义了以下方法:
- (void)catchTargetAtPoint:(CGPoint)target {
CGPoint cannonPointOnScene = [self.scene convertPoint:self.position fromNode:self.parent];
float angle = [CannonNode pointPairToBearingDegreesWithStartingPoint:cannonPointInScene endingPoint:target];
if (self.zRotation < 0) {
self.zRotation = self.zRotation + M_PI * 2;
}
if ((angle < self.maxAngle) && (angle> self.minAngle)) {
[self runAction:[SKAction rotateToAngle:angle duration:1.0f]];
}
}
+ (float)pointPairToBearingDegreesWithStartingPoint:(CGPoint)startingPoint endingPoint:(CGPoint) endingPoint {
CGPoint originPoint = CGPointMake(endingPoint.x - startingPoint.x, endingPoint.y - startingPoint.y); // get origin point to origin by subtracting end from start
float bearingRadians = atan2f(originPoint.y, originPoint.x); // get bearing in radians
return bearingRadians;
}
catchTargetAtPoint
必须在场景的 update
方法中调用。
关于objective-c - iOS Sprite Kit 如何在横向方向上使弹丸指向目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128923/