当前位置:网站首页>Phaser (I): platform jumping collection game
Phaser (I): platform jumping collection game
2022-07-26 04:32:00 【Prosper Lee】
Effect display

Project structures,
$ npm init [email protected] my-game --template vanilla-ts
$ cd my-game
$ npm i
$ npm install phaser
$ npm run dev
introduce Phaser
import Phaser from 'phaser';
Game item initialization

import Phaser from 'phaser';
export default class SampleScene extends Phaser.Scene {
constructor() {
// super(config); config Scenario specific configuration parameters
super('SampleScene');
}
// Initialization callback of scenario
init() {
console.log('init');
}
// Preload callback of scenario
preload() {
console.log('preload');
}
// Callback of scenario creation
create() {
console.log('create');
}
/** * Scene update callback * @param time current time * @param delta Incremental time since the last frame ( millisecond ). This is based on FPS Smoothing and capping values of rates */
update(time: number, delta: number) {
super.update(time, delta);
}
}
const config: Phaser.Types.Core.GameConfig = {
// Rendering mode
type: Phaser.AUTO,
width: 800,
height: 600,
// Physical configuration
physics: {
// Default physical system
default: 'arcade', // arcade impact matter
// arcade Physical configuration
arcade: {
// gravity
gravity: {
y: 300},
debug: true
}
},
// scene
scene: SampleScene
}
const game: Phaser.Game = new Phaser.Game(config);
console.log(game);
resources

Initialization background

export default class SampleScene extends Phaser.Scene {
/* ···CODE··· */
// Preload callback of scenario
preload() {
// Get the address of the background resource in the scene
const {
href: sky} = new URL(`assets/resources/sky.png`, import.meta.url);
// load resources
this.load.image('sky', sky);
}
// Callback of scenario creation
create() {
// Add resources to the scene
this.add.image(400, 300, 'sky');
}
/* ···CODE··· */
}
Initialize platform

export default class SampleScene extends Phaser.Scene {
// platform
private platforms: Phaser.Physics.Arcade.StaticGroup | undefined;
/* ···CODE··· */
// Preload callback of scenario
preload() {
// Get the address of the background resource in the scene
const {
href: sky} = new URL(`assets/resources/sky.png`, import.meta.url);
// Get the address of the platform resource in the scene
const {
href: ground} = new URL(`assets/resources/platform.png`, import.meta.url);
// load resources
this.load.image('sky', sky);
this.load.image('ground', ground);
}
// Callback of scenario creation
create() {
// Add resources to the scene
this.add.image(400, 300, 'sky');
// Add platforms
this.platforms = this.physics.add.staticGroup(); // Static physical object group
// Zoom in on the platform flat and refresh the platform rigid body
this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
// Place other platforms
this.platforms.create(600, 400, 'ground');
this.platforms.create(50, 250, 'ground');
this.platforms.create(750, 220, 'ground');
}
/* ···CODE··· */
}
Initialize stars

export default class SampleScene extends Phaser.Scene {
// platform
private platforms: Phaser.Physics.Arcade.StaticGroup | undefined;
// The stars
private stars: Phaser.Physics.Arcade.Group | undefined;
preload() {
/* ···CODE··· */
const {
href: star} = new URL(`assets/resources/star.png`, import.meta.url);
this.load.image('star', star);
/* ···CODE··· */
}
create() {
/* ···CODE··· */
// Add stars
this.stars = this.physics.add.group({
key: 'star',
repeat: 9, // Add number n+1
setXY: {
x: 20, y: 0, stepX: 84} // every other 84 Place an offset of 20 The stars of
});
// Random elasticity
this.stars.children.iterate((child) => {
child.body.gameObject.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
});
// Add collider ( Stars collide with the ground )
this.physics.add.collider(this.stars, this.platforms);
/* ···CODE··· */
}
/* ···CODE··· */
}
Initialize player
Configure whether the player collides with the world boundary

export default class SampleScene extends Phaser.Scene {
// The player
private player: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody | undefined;
preload() {
const {
href: dude} = new URL(`assets/resources/dude.png`, import.meta.url);
this.load.spritesheet('dude', dude, {
frameWidth: 32, frameHeight: 48});
}
create() {
// Add players
this.player = this.physics.add.sprite(100, 450, 'dude');
this.player.setCollideWorldBounds(true); // Set whether this entity collides with the world boundary
}
}
Configure the player to collide with the ground

export default class SampleScene extends Phaser.Scene {
// The player
private player: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody | undefined;
preload() {
const {
href: dude} = new URL(`assets/resources/dude.png`, import.meta.url);
this.load.spritesheet('dude', dude, {
frameWidth: 32, frameHeight: 48});
}
create() {
// Add players
this.player = this.physics.add.sprite(100, 450, 'dude');
this.player.setCollideWorldBounds(true); // Set whether this entity collides with the world boundary
this.physics.add.collider(this.player, this.platforms);
}
}
Configure player animation

export default class SampleScene extends Phaser.Scene {
create() {
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', {
start: 0, end: 3}),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [{
key: 'dude', frame: 4}],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', {
start: 5, end: 8}),
frameRate: 10,
repeat: -1
});
this.player!.anims.play('left', true);
// this.player!.anims.play('turn', true);
// this.player!.anims.play('right', true);
}
}
Configure the mouse to control the player and play the animation

export default class SampleScene extends Phaser.Scene {
// Keyboard monitor
private cursors: Phaser.Types.Input.Keyboard.CursorKeys | undefined;
create() {
// Add direction control
this.cursors = this.input.keyboard.createCursorKeys();
}
/** * Scene update callback * @param time current time * @param delta Incremental time since the last frame ( millisecond ). This is based on FPS Smoothing and capping values of rates */
update(time: number, delta: number) {
super.update(time, delta);
// Control direction
if (this.cursors!.left.isDown) {
// Left
this.player!.setVelocityX(-160);
this.player!.anims.play('left', true);
} else if (this.cursors!.right.isDown) {
// Right
this.player!.setVelocityX(160);
this.player!.anims.play('right', true);
} else {
// stop it
this.player!.setVelocityX(0);
this.player!.anims.play('turn');
}
// jumping ( Continuous jumping is not supported )
if (this.cursors!.up.isDown && this.player!.body.touching.down) {
this.player!.setVelocityY(-330);
}
}
}
Add score text

export default class SampleScene extends Phaser.Scene {
// fraction
private score: number = 0;
// Text
private scoreText: Phaser.GameObjects.Text | undefined;
create() {
// To add text
this.scoreText = this.add.text(16, 16, `Score: ${
this.score}`, {
fontSize: '32px'});
}
}
Collect stars and add points - Check for collisions

export default class SampleScene extends Phaser.Scene {
create() {
// Detect player and star overlap
this.physics.add.overlap(this.player, this.stars, this.collectStar, undefined, this);
}
// Collect stars
collectStar(player: Phaser.Types.Physics.Arcade.GameObjectWithBody, star: Phaser.Types.Physics.Arcade.GameObjectWithBody) {
star.body.gameObject.disableBody(true, true);
this.score += 10;
this.scoreText!.setText(`Score: ${
this.score}`);
}
}
When the stars are collected, add the stars again

export default class SampleScene extends Phaser.Scene {
// Collect stars
collectStar(player: Phaser.Types.Physics.Arcade.GameObjectWithBody, star: Phaser.Types.Physics.Arcade.GameObjectWithBody) {
// The number of stars is 0 Recreate the stars
if (this.stars!.countActive(true) === 0) {
this.stars!.children.iterate((child) => {
child.body.gameObject.enableBody(true, child.body.gameObject.x, 0, true, true);
});
}
}
}
Add enemies
Every time the player collects all the planets, he adds an automatic bouncing ball as the enemy

export default class SampleScene extends Phaser.Scene {
// The enemy
private bombs: Phaser.Physics.Arcade.Group | undefined;
preload() {
const {
href: bomb} = new URL(`assets/resources/bomb.png`, import.meta.url);
this.load.image('bomb', bomb);
}
create() {
// Add enemies
this.bombs = this.physics.add.group();
this.physics.add.collider(this.bombs, this.platforms);
}
// Collect stars
collectStar(player: Phaser.Types.Physics.Arcade.GameObjectWithBody, star: Phaser.Types.Physics.Arcade.GameObjectWithBody) {
star.body.gameObject.disableBody(true, true);
this.score += 10;
this.scoreText!.setText(`Score: ${
this.score}`);
// The number of stars is 0 Recreate the stars
if (this.stars!.countActive(true) === 0) {
this.stars!.children.iterate((child) => {
child.body.gameObject.enableBody(true, child.body.gameObject.x, 0, true, true);
});
// Add an enemy to the scene
const x = (player.body.gameObject.x < 400) ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);
const bomb = this.bombs!.create(x, 16, 'bomb');
bomb.setBounce(1); // Elastic force
bomb.setCollideWorldBounds(true);
bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
}
}
}
Add collision enemies. The game is over

export default class SampleScene extends Phaser.Scene {
// Is the game over
private gameOver: boolean = false;
create() {
// Add enemies
this.bombs = this.physics.add.group();
this.physics.add.collider(this.bombs, this.platforms);
this.physics.add.collider(this.player, this.bombs, this.hitBomb, undefined, this);
}
update(time: number, delta: number) {
super.update(time, delta);
if (this.gameOver) {
this.scoreText!.setText(` Game over ,Score: ${
this.score}`);
return;
}
}
// Collide with the enemy
hitBomb(player: Phaser.Types.Physics.Arcade.GameObjectWithBody, _bomb: Phaser.Types.Physics.Arcade.GameObjectWithBody) {
// Pause the physics engine
this.physics.pause();
player.body.gameObject.setTint(0xff0000);
player.body.gameObject.anims.play('turn');
this.gameOver = true;
}
}
Complete code
import Phaser from 'phaser';
export default class SampleScene extends Phaser.Scene {
// platform
private platforms: Phaser.Physics.Arcade.StaticGroup | undefined;
// The stars
private stars: Phaser.Physics.Arcade.Group | undefined;
// The player
private player: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody | undefined;
// Keyboard monitor
private cursors: Phaser.Types.Input.Keyboard.CursorKeys | undefined;
// fraction
private score: number = 0;
// Text
private scoreText: Phaser.GameObjects.Text | undefined;
// The enemy
private bombs: Phaser.Physics.Arcade.Group | undefined;
// Is the game over
private gameOver: boolean = false;
constructor() {
// super(config); config Scenario specific configuration parameters
super('SampleScene');
}
// Initialization callback of scenario
init() {
console.log('init');
}
// Preload callback of scenario
preload() {
console.log('preload');
// Get the address of the background resource in the scene
const {
href: sky} = new URL(`assets/resources/sky.png`, import.meta.url);
// Get the address of the platform resource in the scene
const {
href: ground} = new URL(`assets/resources/platform.png`, import.meta.url);
const {
href: star} = new URL(`assets/resources/star.png`, import.meta.url);
const {
href: dude} = new URL(`assets/resources/dude.png`, import.meta.url);
const {
href: bomb} = new URL(`assets/resources/bomb.png`, import.meta.url);
// load resources
this.load.image('sky', sky);
this.load.image('ground', ground);
this.load.image('star', star);
this.load.spritesheet('dude', dude, {
frameWidth: 32, frameHeight: 48});
this.load.image('bomb', bomb);
}
// Callback of scenario creation
create() {
console.log('create');
// Add resources to the scene
this.add.image(400, 300, 'sky');
// Add platforms
this.platforms = this.physics.add.staticGroup(); // Static physical object group
// Zoom in on the platform flat and refresh the platform rigid body
this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
// Place other platforms
this.platforms.create(600, 400, 'ground');
this.platforms.create(50, 250, 'ground');
this.platforms.create(750, 220, 'ground');
// Add stars
this.stars = this.physics.add.group({
key: 'star',
repeat: 9, // Add number n+1
setXY: {
x: 20, y: 0, stepX: 84} // every other 84 Place an offset of 20 The stars of
});
// Random elasticity
this.stars.children.iterate((child) => {
child.body.gameObject.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
});
// Add collider ( Stars collide with the ground )
this.physics.add.collider(this.stars, this.platforms);
// Add players
this.player = this.physics.add.sprite(50, 450, 'dude');
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', {
start: 0, end: 3}),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [{
key: 'dude', frame: 4}],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', {
start: 5, end: 8}),
frameRate: 10,
repeat: -1
});
this.player.setCollideWorldBounds(true); // Set whether this entity collides with the world boundary
this.physics.add.collider(this.player, this.platforms);
// Add direction control
this.cursors = this.input.keyboard.createCursorKeys();
// To add text
this.scoreText = this.add.text(16, 16, `Score: ${
this.score}`, {
fontSize: '32px'});
// Detect player and star overlap
this.physics.add.overlap(this.player, this.stars, this.collectStar, undefined, this);
// Add enemies
this.bombs = this.physics.add.group();
this.physics.add.collider(this.bombs, this.platforms);
this.physics.add.collider(this.player, this.bombs, this.hitBomb, undefined, this);
}
/** * Scene update callback * @param time current time * @param delta Incremental time since the last frame ( millisecond ). This is based on FPS Smoothing and capping values of rates */
update(time: number, delta: number) {
super.update(time, delta);
if (this.gameOver) {
this.scoreText!.setText(` Game over ,Score: ${
this.score}`);
return;
}
// Control direction
if (this.cursors!.left.isDown) {
// Left
this.player!.setVelocityX(-160);
this.player!.anims.play('left', true);
} else if (this.cursors!.right.isDown) {
// Right
this.player!.setVelocityX(160);
this.player!.anims.play('right', true);
} else {
// stop it
this.player!.setVelocityX(0);
this.player!.anims.play('turn');
}
// jumping ( Continuous jumping is not supported )
if (this.cursors!.up.isDown && this.player!.body.touching.down) {
this.player!.setVelocityY(-330);
}
}
// Collect stars
collectStar(player: Phaser.Types.Physics.Arcade.GameObjectWithBody, star: Phaser.Types.Physics.Arcade.GameObjectWithBody) {
star.body.gameObject.disableBody(true, true);
this.score += 10;
this.scoreText!.setText(`Score: ${
this.score}`);
// The number of stars is 0 Recreate the stars
if (this.stars!.countActive(true) === 0) {
this.stars!.children.iterate((child) => {
child.body.gameObject.enableBody(true, child.body.gameObject.x, 0, true, true);
});
// And add an enemy to the scene
const x = (player.body.gameObject.x < 400) ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);
const bomb = this.bombs!.create(x, 16, 'bomb');
bomb.setBounce(1); // Elastic force
bomb.setCollideWorldBounds(true);
bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
}
}
// Collide with the enemy
hitBomb(player: Phaser.Types.Physics.Arcade.GameObjectWithBody, _bomb: Phaser.Types.Physics.Arcade.GameObjectWithBody) {
// Pause the physics engine
this.physics.pause();
player.body.gameObject.setTint(0xff0000);
player.body.gameObject.anims.play('turn');
this.gameOver = true;
}
}
const config: Phaser.Types.Core.GameConfig = {
// Rendering mode
type: Phaser.AUTO,
width: 800,
height: 600,
// Physical configuration
physics: {
// Default physical system
default: 'arcade', // arcade impact matter
// arcade Physical configuration
arcade: {
// gravity
gravity: {
y: 300},
debug: true
}
},
// scene
scene: SampleScene
}
const game: Phaser.Game = new Phaser.Game(config);
console.log(game);
边栏推荐
- A series of problems about the number of DP paths
- Use Baidu PaddlePaddle easydl to complete garbage classification
- 数组排序1
- Why is mongodb fast
- 2022 a.static query on tree (tree section)
- 嵌入式实操----基于RT1170 FreeRTOS实现CPU使用率统计(二十四)
- Function knowledge points
- Solve the error string value: '\xf0\x9f\x98\xad',... 'for column' commentcontent 'at row 1
- Design and implementation of smart campus applet based on cloud development
- 【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(八)
猜你喜欢

Segger embedded studio cannot find xxx.c or xxx.h file

ASP. Net core actionfilter filter details

2022 Henan Mengxin League game (3): Henan University L - synthetic game

TIA botu WinCC Pro controls the display and hiding of layers through scripts
![[C language foundation] 13 preprocessor](/img/4c/ab25d88e9a0cf29bde6e33a2b14225.jpg)
[C language foundation] 13 preprocessor

数组排序2

egg-ts-sequelize-CLI

七、RESTful

这种是我的vs没连上数据库吗

1. Excel的IF函数
随机推荐
Use of anonymous functions
Face database collection summary
data warehouse
FFmpeg 视频添加水印
Several methods of realizing high-low byte or high-low word exchange in TIA botu s7-1200
人脸数据库收集总结
UE4 switching of control rights of multiple roles
Page pull-up refresh and pull-down loading
How to write the introduction and conclusion of an overview paper?
egg-ts-sequelize-CLI
Network Security Learning - permission promotion 2
Life related -- the heartfelt words of a graduate tutor of Huake (mainly applicable to science and Engineering)
autocomplete禁止表单自动填充
1. If function of Excel
Day24 job
SwiftUI一日速成
1. Excel的IF函数
Acwing brush questions
How to build an automated testing framework?
Array sort 2