Previous Phaser tutorials:
Phaser tutorial: DronShooter - simple game in Typescript - Part 2
Phaser tutorial: adding 9-patch image support to Phaser
Phaser tutorial: DronShooter - simple game in Typescript - Part 1
Phaser tutorial: custom easing functions for tweening and easing functions with parameters
Phaser tutorial: sprites and custom properties for atlas frames
Phaser tutorial: manage different screen sizes
Phaser tutorial: How to wrap bitmap text
First adjust your State class with adding some constants and private variables and also delete most of the create() method:
Next add new lines into create() method:
The first line creates cannon barrel sprite and places it in the middle bootom. Next we adjust anchor of it as shown on this image:
If you now compile and run you should see this construct in the bottom of the screen:
Now, let's move it. Add next few lines to create() method:
We check left and right key and if pressed (isDown()), then we adjust cannon rotation. The speed of rotation is π/4 in sec. by CANNON_SPEED, which is 2. So, cannon is rotation with speed π/2 in second.
Now we have drone and moving cannon. Next, we will spawn swarm of drones. Our dron class is ready from previous part, so this will should be easy. Add few private variables to State class:
And add next lines to create method:
Callback method hitDrone() is called by P2 engine with two parameters - first is drone that collided and second is object it collided with. All we do, is let the drone explode and we kill missile. If you recall explode() method in our Drone class, you will remember that after explosion animation is finished, drone is killed too.
Similarly to drones, we add missiles in create() method:
With these color debug circles all deadly drones now looks like jolly carnival balloons:
In first line we ask for free missile in group. It works like pool. When we created missiles, all of them were set exists = false. Now, we want to find first that does not exist, revive it and after it is killed (or its time expires), it falls into exists = false again.
We check, whether we got any free missile. If yes, we calculate position on the tip of cannon barrel and set with reset() method position of missile. Calling reset sets exists = true. Rotation of the missile is the same as rotation of cannon. Lifetime of missile is limited to 1.5 second. If this time is expired, missile falls automatically into exists = false and is ready for reuse.
If you compile and run now, you can move your cannon left to right with arrow keys. With space bar you can launch missiles and shoot drones.
During tutorial we created very simple game in less than 240 lines - see full listing bellow or download whole project.
While it is simple, it creates our Dron class derived from Phaser.Sprite, we use animations and custom tweening function, we handle input and also use P2 physics.
Here is our final game in action: