我在太空射击游戏中有一个寻热导弹跟随一个移动的目标。导弹跟随移动目标足够好,但我希望它能够不断向目标方向旋转。我目前的代码如下:
-(void)updateHeatSeekerAngleTo:(CGPoint)direction
{
CGFloat angle = atan2f(direction.y, direction.x);
_heatSeeker.zRotation = angle;
}
然后在didSimulatePhysics中调用此方法(因为这比使用以下更新:):
[self updateHeatSeekerAngleTo:_target.position];
如前所述,导弹精美地跟随移动目标,然而,它具有非常延迟的旋转效果,并且经常在侧向位置跟随移动目标,然后当它越近时最终指向目标。我在静止的导弹精灵上测试了代码,当目标移动时,固定导弹不断地指向目标,但是当导弹运动时它不会这样做。怎样才能使导弹在运动中不断指向移动目标?
答案 0 :(得分:1)
当你向其发射导弹时,听起来你的目标正在部署对策......
除了笑话,我怀疑这可能是你没有考虑的90度偏移。节点的zRotation"零"角度实际上在节点的右边,或者我们会考虑90度。这可能会在处理角度时出现很多混乱,零点直接上升。查看下面的示例项目代码。您可以点击/单击并拖动屏幕周围的方块,导弹尖端将跟踪目标。您可以使用该代码来纠正您的问题。
#import "GameScene.h"
@implementation GameScene {
SKSpriteNode *node0;
SKSpriteNode *node1;
}
-(void)didMoveToView:(SKView *)view {
self.backgroundColor = [SKColor whiteColor];
node0 = [SKSpriteNode spriteNodeWithColor:[SKColor grayColor] size:CGSizeMake(50, 50)];
node0.position = CGPointMake(500, 500);
[self addChild:node0];
node1 = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:CGSizeMake(10, 50)];
node1.position = CGPointMake(300, 350);
[self addChild:node1];
SKSpriteNode *node0Tip = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(10, 10)];
node0Tip.position = CGPointMake(0, 25);
[node1 addChild:node0Tip];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint touchLocation = [touch locationInNode:self];
node0.position = touchLocation;
// calculate angle between object and touch
float deltaY = touchLocation.y - node1.position.y;
float deltaX = touchLocation.x - node1.position.x;
float moveBydegrees = atan2(deltaY, deltaX) * 180 / 3.14159265359;
// convert degrees to radians
float moveByRadians = moveBydegrees * M_PI / 180;
node1.zRotation = (moveByRadians-1.5707963268); // account for 90 degree offset
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint touchLocation = [touch locationInNode:self];
node0.position = touchLocation;
// calculate angle between object and touch
float deltaY = touchLocation.y - node1.position.y;
float deltaX = touchLocation.x - node1.position.x;
float moveBydegrees = atan2(deltaY, deltaX) * 180 / 3.14159265359;
// convert degrees to radians
float moveByRadians = moveBydegrees * M_PI / 180;
node1.zRotation = (moveByRadians-1.5707963268); // account for 90 degree offset
}
}