下面是如何確定一個例子,如果一個節點內另一個節點的視野。如果將角度轉換爲[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");
}