Next add the following variable declarations to your GameScene.swift file.
Next add the following code to your GameScene.swift file, bellow the didMoveToView method.
Here is where you add the overrides to handle the touch inputs, this example is a control scheme that I did not come up with, where you touch the screen and the ship quickly moves to that position then you drag around and the ship follows, also you fire the weapon at the same time, for a mobile platform with touch screen only in my opinion the one touch controls are best to be able to enjoy the game, rather than be trying to push small buttons on screen.
Now add an important function that will be called to fire a projectile.
This function does the following:
- You create a SKSpriteNode that will be the projectile, then position it to the ship coordinates offset y by the ships height divided by 2 to make the laser ball come off the tip of the ship.
- Then the simple v = d/t which you rearrange for time is now t = d/v as you can see travelTime for the projectile is distance divided by speed, you can change the speed value to make to projectiles faster or slower, this calculation is done because if you move your ship through the screen the distance between the start point and the top of the screen changes and projectiles would fire slower as you go higher on the screen, this way the speed remains constant.
- Next you run a sequence of actions on the projectile so that it will travel to the set point at the top of the screen, and then it will remove itself from the scene.
- The timeSinceLastFire variable is there to control the rate of fire since this will get called by the update method of your GameScene which gets called before each frame, that means if the game is running well it would be 60 times in 1 second, here I add delta to this value then check if the appropriate time has passed before firing another projectile.
Last you make your update override function look like this:
Build and Run the project you should see the same scene only now you can touch and the ship move and shoots!
Here is the entire GameScene.swift file as it is after Step #2:
On the next step we will add something to shoot at because empty outer space can be boring.