当前位置:网站首页>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);
边栏推荐
- 自动化测试框架该如何搭建?
- Tutorial on using the one click upgrade function of the rtsp/onvif protocol video platform easynvr service
- QT compilation error sorting and remote module Download
- Keil V5 installation and use
- Steam science education endows classroom teaching with creativity
- 1、 Basic introduction
- [C language foundation] 13 preprocessor
- The auxiliary role of rational cognitive educational robot in teaching and entertainment
- Array sort 3
- 1. If function of Excel
猜你喜欢

Acwing brush questions

UE4 靠近物体时显示文字,远离时文字消失
![[C language foundation] 13 preprocessor](/img/4c/ab25d88e9a0cf29bde6e33a2b14225.jpg)
[C language foundation] 13 preprocessor

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

Offline installation of idea plug-in (continuous update)

Keil V5 installation and use

Postman imports curl, exports curl, and exports corresponding language codes

解析Steam教育的课程设计测评体系

建设面向青少年的创客教育实验室

Creative design principle of youth maker Education
随机推荐
【学习笔记】AGC041
解析Steam教育的课程设计测评体系
Analyzing the curriculum design evaluation system of steam Education
Autocomplete prevents the form from automatically filling in
Sangi diagram of machine learning (for user behavior analysis)
How to build an automated testing framework?
使用百度飞桨EasyDL完成垃圾分类
Throttling anti shake function of JS handwritten function
Steam science education endows classroom teaching with creativity
一、基础入门
egg-ts-sequelize-CLI
2022 Henan Mengxin League game (3): Henan University L - synthetic game
理性认知教育机器人寓教于乐的辅助作用
UE4 keyboard control switch light
Codeforces Round #807 (Div. 2)
ASP. Net core actionfilter filter details
Function knowledge points
Add watermark to ffmpeg video
Why is mongodb fast
UE4 switching of control rights of multiple roles