applyImpulse对CGPoint SpriteKit

时间:2014-03-03 20:50:01

标签: sprite-kit cgpoint sknode

我是SpriteKit中的新手,游戏开发者,事实上我只是在学习。所以我得到了一个点,我将一堆节点移动到用户点击位置。到目前为止,我一直在努力计算一个虚拟的直角三角形,并根据边来获得角度和角度。不幸的是,这给我留下了非常强烈的冲动,并没有真正考虑用户点击位置。

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:4)

在Ray Wenderlich的教程中查看射击射弹部分:

http://www.raywenderlich.com/42699/spritekit-tutorial-for-beginners

按如下方式更改教程中的代码:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    // 1 - Choose one of the touches to work with
    UITouch * touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    // 2 - Set up initial location of projectile
    SKSpriteNode * projectile = [self childNodeWithName:@"desirednode"];
    //make projectile point to your desired node.

    // 3- Determine offset of location to projectile
    CGPoint offset = rwSub(location, projectile.position);

    // 4 - Bail out if you are shooting down or backwards. You can ignore this if required.
    if (offset.x <= 0) return;

    // 5 - OK to add now - we've double checked position
    [self addChild:projectile];

    // 6 - Get the direction of where to shoot
    CGPoint direction = rwNormalize(offset);

    // 7 - Make it shoot far enough to be guaranteed off screen
    float forceValue = 200; //Edit this value to get the desired force.
    CGPoint shootAmount = rwMult(direction, forceValue);

    //8 - Convert the point to a vector
    CGVector impulseVector = CGVectorMake(shootAmount.x, shootAmount.y);
    //This vector is the impulse you are looking for.

    //9 - Apply impulse to node.
    [projectile.physicsBody applyImpulse:impulseVector];

}

代码中的射弹对象代表您的节点。此外,您需要编辑forceValue以获得所需的冲动。