We added collision detection between the players bullet and the enemy, as well as the player and enemy bullets in the previous example. To make it a bit more challenging to hit the enemy, we will make the enemy move.
There are certainly lots of different ways of moving sprites around the screen. For example, you could simply set the velocity of the sprite body so that it moves in a straight line until it flies out of the screen. You could set other physics body parameters to move the sprites in many different ways.
Phaser actually provides a very powerful function called Tweens which allows you to manipulate the sprite body's parameters in many sophisticated ways. To illustrate the power of this function, I have poached from an example in the Phaser discourse group, here. The relevant code is as below.
enemyMoving = this.tweens.add({
targets: enemy.body.velocity,
props: {
x: { from: 150, to: -150, duration: 4000 },
y: { from: 50, to: -50, duration: 2000 }
},
ease: "Sine.easeInOut",
yoyo: true,
repeat: -1
});
The above few lines of code makes the enemy character move in an undulating pattern around the screen. I will leave it up to you to look at the detail by referring to the official Phaser documentation.
As the enemy object is created separately from the danmaku object which is firing the bullets, I have added a method to the danmaku object called follow(object) to set the position of the danmaku to that of the object passed to it as a parameter. Calling this function from the main update function allows us the danmaku to track the enemy and hence the enemy to appear firing the danmaku.
As always, I have once again changed the names of some of the variables. For example, I have changed the x and y coordinates of the danmaku class to simply x and y from danmakuPosX and danmakuPosY; ie the default parameters of the game object that the danmaku class is. This is a throwback to my very very originamku danmaku code whih was not a game object.
The CodePen is available here, for your perusal.
コメント