objective-c - iOS Sprite Kit 如何在横向方向上使弹丸指向目标?

标签 objective-c ios7 rotation geometry sprite-kit

我的 sprite 套件游戏中有一个图标,我打算将其用作一个角色射击另一个角色时的动画射弹。我正在尝试调整这个射弹的方向以指向目标。

enter image description here

我将它旋转 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/

相关文章:

ios - 尝试对地址进行地址解析并获取kCLErrorGeocodeFoundNoResult

objective-c - 我可以收到发送 nil objects 消息的警告吗?

ios - 耳机插好了吗? IOS 7

objective-c - 保存后 NSManagedObject 更改了属性

iphone - 禁止在 subview 上接收来自父 View 的触摸

objective-c - 当使用 NSOperation 在 iOS 7 中使用 Background Fetch 调用 completionHandler

uiviewcontroller - 水平分隔符 NavBar IOS 7

html - 两轴旋转​​在css 3d旋转中发生碰撞

javascript - 如何将 x->n y->n 对象顺时针旋转 90°?

file - 实现Semi-Round-Robin文件,可按需扩展和保存