在SpriteKit旋转坐标系的视野中

时间:2014-11-24 04:54:57

标签: ios objective-c math sprite-kit trigonometry

SpriteKit的旋转坐标系很难处理,不用说。

数学上,这是一场彻底的灾难。

我有一个视野, x ,这样最左边的视图是θ+ x ,最右边的视图是θ-x θ是精灵的zRotation。

如何检查角度是否在另一个视野中?

let λ be atan2(test.y - char.y, test.x - char.x)
let θ be char.zRotation
if λ in θ - x, θ + x
    return true

This makes no sense

2 个答案:

答案 0 :(得分:0)

如果将角度夹在PI和-PI之间,则数学运算会更简单:

let PI=CGFloat(M_PI)

var spriteAngle:CGFloat=0
let fieldOfView:CGFloat=0.5
var targetAngle:CGFloat=0

while spriteAngle>PI {
   spriteAngle=spriteAngle-2*PI
}
while spriteAngle < -PI {
    spriteAngle=spriteAngle+2*PI
}
while targetAngle>PI {
    targetAngle=targetAngle-2*PI
}
while targetAngle < -PI {
    targetAngle=targetAngle+2*PI
}

let lowerBound=spriteAngle-fieldOfView
let upperBound=spriteAngle+fieldOfView

if lowerBound <= targetAngle && targetAngle <= upperBound {
    //angle in range
}

答案 1 :(得分:0)

这是一个如何确定节点是否在另一个节点的视野范围内的示例。如果将角度转换为[0,2 * pi),则相当简单。

    // 1/2 of the field of view
    #define kFieldOfViewDiv2    (M_PI/8)

    // Calculate differences in x and y between the sprites
    CGFloat dx = sprite2.position.x - sprite.position.x;
    CGFloat dy = sprite2.position.y - sprite.position.y;
    // Determine angle of sprite2 relative to sprite
    CGFloat theta = atan2(dy, dx);
    // Theta in [0, 2*pi)
    if (theta < 0) {
        theta = theta + M_PI*2;
    }
    // Alpha in (-2*pi, 2*pi)
    CGFloat alpha = fmod(sprite.zRotation,2*M_PI);
    // Alpha in [0, 2*pi)
    if (alpha < 0) {
        alpha = alpha + M_PI * 2;
    }
    // Calculate |theta-alpha|
    CGFloat diff = fabs(theta-alpha);
    // Handle wrap near 0 degrees
    if (diff > M_PI) {
        diff = 2*M_PI - diff;
    }
    // Field of view test
    if (diff <= kFieldOfViewDiv2) {
        NSLog(@"In field of view");
    }