官术网_书友最值得收藏!

Bumping bees into bees

You may have noticed that we positioned bee2 and bee3 at the same height in the game world. We only need to push one of them horizontally to create a collision—perfect crash test dummies! We can use an impulse to create velocity for the outside bee.

Locate the didMove function in GameScene.swift. At the bottom, after all of our spawn code, add this line:

bee2.physicsBody?.applyImpulse(CGVector(dx: -3, dy: 0)) 

Run the project. You will see the outermost bee fly toward the middle and crash into the inner bee. This pushes the inner bee to the left and slows the first bee from the contact.

Attempt the same experiment with a variable: increased mass. Before the impulse line, add this code to adjust the mass of bee2:

bee2.physicsBody?.mass = 0.2 

Run the project. Hmm—our heavier bee does not move very far with the same impulse (it is a 200-gram bee, after all). It eventually bumps into the inner bee, but it is not a very exciting collision. We will need to crank up the impulse to propel our beefier bee. Change the impulse line to use a dx value of -25:

bee2.physicsBody?.applyImpulse(CGVector(dx: -25, dy: 0)) 

Run the project again. This time, our impulse provides enough energy to move the heavy bee in an interesting way. Notice how much energy the heavy bee transfers to the normal bee when they collide. Both bees possess enough momentum to eventually slide completely off the screen. Your simulator should look something like this screenshot, just before the bees slide off the screen:

Bumping bees into bees

Before you move on, you may wish to experiment with the various physics properties that I outlined earlier in this chapter. You can create many collision variations; the physics simulation offers a lot of depth without much effort.

Movement with impulses and forces

You have several options for moving nodes with physics bodies:

  • An impulse is an immediate, one-time change to a physics body's velocity. In our test, an impulse gave the bee its velocity and it slowly bled speed to damping and its collision. Impulses are perfect for projectiles, such as missiles, bullets, disgruntled birds, and so on.
  • A force applies velocity for only one physics calculation cycle. When we use a force, we typically apply it before every frame. Forces are useful for rocket ships, cars, or anything else that is continually self-propelled.
  • You can also edit the velocity and angularVelocity properties of a body directly. This is useful for setting a manual velocity limit.

Note

Checkpoint 3-B

The code up to this point is available in the chapter's code resources.

主站蜘蛛池模板: 安化县| 寻乌县| 松江区| 垫江县| 鄂州市| 盐源县| 星座| 大安市| 呼和浩特市| 齐齐哈尔市| 于都县| 三河市| 玛多县| 伊川县| 拉萨市| 冷水江市| 常熟市| 合水县| 丰顺县| 桑日县| 土默特右旗| 曲靖市| 萝北县| 龙山县| 会东县| 望都县| 许昌市| 万源市| 花莲市| 安陆市| 大邑县| 泽普县| 灵寿县| 丰城市| 沅江市| 镇安县| 霸州市| 保定市| 延吉市| 肥东县| 扬州市|