Sprite Kit - Apply Impulse to shoot projectile at character

后端 未结 1 647
别跟我提以往
别跟我提以往 2021-01-03 04:17

I am developing a game using Sprite-Kit (Objective-C). It\'s a game where you control a bird in flight and arrows and other bad projectiles are shot at you from the right/to

相关标签:
1条回答
  • 2021-01-03 04:34

    The basic steps are

    1. Calculate vector components from the projectile launcher to the bird
    2. Normalize the components (optional)
    3. Create a vector by scaling the (normalized) components
    4. Apply impulse to the projectile using the vector

    Here's an example of how to do that

    Obj-C

    // Calculate vector components x and y
    CGFloat dx = bird.position.x - launcher.position.x;
    CGFloat dy = bird.position.y - launcher.position.y;
    
    // Normalize the components
    CGFloat magnitude = sqrt(dx*dx+dy*dy);
    dx /= magnitude;
    dy /= magnitude;
    
    // Create a vector in the direction of the bird
    CGVector vector = CGVectorMake(strength*dx, strength*dy);
    
    // Apply impulse
    [projectile.physicsBody applyImpulse:vector];
    

    Swift

    // Calculate vector components x and y
    var dx = bird.position.x - launcher.position.x
    var dy = bird.position.y - launcher.position.y
    
    // Normalize the components
    let magnitude = sqrt(dx*dx+dy*dy)
    dx /= magnitude
    dy /= magnitude
    
    // Create a vector in the direction of the bird
    let vector = CGVector(dx:strength*dx, dy:strength*dy)
    
    // Apply impulse
    projectile.physicsBody?.applyImpulse(vector)
    
    0 讨论(0)
提交回复
热议问题