How to get Phaser 3 to output final score - javascript

I'm creating my first Phaser 3 game and I need to output the final score to be used by another .js file that will output to a mysql database. I also need to be able to import the current highscore from said database into the phaser game.
final score is stores and var finalScore
database table name is highScores with the columns id, userName, score, date (date is so we can sort high scores by all time high scores, monthly high scores and daily high scores)
But I just need help getting the finalScore out of phaser and currentHighScore into phaser
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Making your first Phaser 3 Game - Part 10</title>
<script src="//cdn.jsdelivr.net/npm/phaser#3.11.0/dist/phaser.js"></script>
<style type="text/css">
body {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var player;
var stars;
var bombs;
var platforms;
var cursors;
var score = 0;
var gameOver = false;
var scoreText;
// var userName;
var game = new Phaser.Game(config);
function preload() {
this.load.image('sky', 'assets/sky.png');
this.load.image('ground', 'assets/platform.png');
this.load.image('star', 'assets/star.png');
this.load.image('bomb', 'assets/bomb.png');
this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
}
function create() {
// A simple background for our game
this.add.image(400, 300, 'sky');
// The platforms group contains the ground and the 2 ledges we can jump on
platforms = this.physics.add.staticGroup();
// Here we create the ground.
// Scale it to fit the width of the game (the original sprite is 400x32 in size)
platforms.create(400, 568, 'ground').setScale(2).refreshBody();
// Now let's create some ledges
platforms.create(600, 400, 'ground');
platforms.create(50, 250, 'ground');
platforms.create(750, 220, 'ground');
// The player and its settings
player = this.physics.add.sprite(100, 450, 'dude');
// Player physics properties. Give the little guy a slight bounce.
player.setBounce(0.2);
player.setCollideWorldBounds(true);
// Our player animations, turning, walking left and walking right.
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
});
// Input Events
cursors = this.input.keyboard.createCursorKeys();
// Some stars to collect, 12 in total, evenly spaced 70 pixels apart along the x axis
stars = this.physics.add.group({
key: 'star',
repeat: 11,
setXY: { x: 12, y: 0, stepX: 70 }
});
stars.children.iterate(function (child) {
// Give each star a slightly different bounce
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
});
bombs = this.physics.add.group();
// The score
scoreText = this.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });
// Collide the player and the stars with the platforms
this.physics.add.collider(player, platforms);
this.physics.add.collider(stars, platforms);
this.physics.add.collider(bombs, platforms);
// Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
this.physics.add.overlap(player, stars, collectStar, null, this);
this.physics.add.collider(player, bombs, hitBomb, null, this);
}
function update() {
if (gameOver) {
var timeStamp = Math.floor(Date.now()) / 1000;
// gets the userName from the player
var userName = prompt("Please enter your name", "name");
//localStorage.setItem("playerName", userName);
// Save score to final score, score will be reset to zero when game restarts
finalScore = score;
console.log("User: " + userName + "'s score is " + finalScore + " at " + timeStamp + ".");
// Reset gameOver to prevent update() loop and prepare game to restart
gameOver = false;
window.confirm("Would you like to play again?");
// add call to start function again
// if (confirm("Press a button!")) {
// this.game.state.restart()
// } else {
return;
// }
}
if (cursors.left.isDown) {
player.setVelocityX(-160);
player.anims.play('left', true);
}
else if (cursors.right.isDown) {
player.setVelocityX(160);
player.anims.play('right', true);
}
else {
player.setVelocityX(0);
player.anims.play('turn');
}
if (cursors.up.isDown && player.body.touching.down) {
player.setVelocityY(-330);
}
}
function collectStar(player, star) {
star.disableBody(true, true);
// Add and update the score
score += 10;
scoreText.setText('Score: ' + score);
if (stars.countActive(true) === 0) {
// A new batch of stars to collect
stars.children.iterate(function (child) {
child.enableBody(true, child.x, 0, true, true);
});
var x = (player.x < 400) ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);
var bomb = bombs.create(x, 16, 'bomb');
bomb.setBounce(1);
bomb.setCollideWorldBounds(true);
bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
bomb.allowGravity = false;
}
}
function hitBomb(player, bomb) {
this.physics.pause();
player.setTint(0xff0000);
player.anims.play('turn');
gameOver = true;
}
// Function to post data to database
// need to get api input format from Zack
module.exports = {
userName: userName,
score: finalScore,
last_date: timeStamp
};
</script>
</body>
</html>

Use Ajax to send the high score to a specific page and then you can use $_POST in PHP to put it in your database. You can use PHP to save the date, time, score, username, etc. Ensure the game name is unique & use that for PHP to reference which index in the database table you created for game scores.
Here is an example save function from games I help develop (for IBP Arcade or SMF Arcade):
function submitScore(score)
{
let pathArray = window.location.pathname.split('/'), newpath = '', currentPath = '';
for (i = 0; i < pathArray.length; i++) {
currentPath = pathArray[i].toString().toLowerCase();
if (currentPath == 'arcade' || currentPath == 'games')
break;
newpath += '/' + pathArray[i];
}
scorepost(window.location.protocol + '//' + window.location.hostname.replace(/[/]+$/, '') + '/' + newpath.replace(/^[/]+/, '') + '/index.php?act=Arcade&do=newscore', {
gname : 'html5_game_name',
gscore: score
});
}
You'll likely have to edit how it determines the URL a bit. The above function was made for 2 different Arcade's and is designed to work for websites contained in either parent or sub-paths.
Call that function right where you have it using the console log.
To get the high scores from your database to be accessible in your game you can use PHP to create an API page with the basic sought data. Use javascript to call the page with the game name as a reference & then use DOM to gather the data. The HTML on the API page can be contained in a parent pre tag. You can use DOM to access its children that has the data like date, score, user name, etc.

Related

Randomly spawn an object when enemies die Phaser 3

I would like to randomly spawn a sprite when an enemy dies.
Example: There is a 1 in 5 chance that when an enemy dies, it drops an object (sprites that increase your HP).
Any idea how this can be done?
I did some research, but I didn't find much.
For randomness in a Phaser application, I would use the Phaser's Math helper function Between (here is the link to the documentation).
It creates a random number (whole number) from the first number to the last one (including the last number, perfect for dice).
So for 1 in 5, you just need to select one number from the interval like 5and compare it with a call to the Between function. And only if it matches, you drop/create the sprite.
Just like this:
if(Phaser.Math.Between(1, 5) === 5){
// .. drop "loot" / health-object
}
Here a small Demo:
(In this demo something could be dropped or not, depending on your luck. 20% is pretty low)
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
scene: {
create
},
banner: false
};
function create () {
this.add.text(10, 10, 'Click to red Boxes')
let graphics = this.make.graphics({x: 0, y: 0, add: false});
graphics.fillStyle(0xFF0000);
graphics.fillRect(0, 0, 20, 20);
graphics.generateTexture('enemy', 20, 20)
let enemiesGroup = this.add.group({
defaultKey: 'enemy',
maxSize: 10
});
let maxEnemiesToShow = 10
for(let idx = 0; idx < maxEnemiesToShow; idx++){
// here the function is used to spawn enemies randomly on screen
const x = Phaser.Math.Between(20, config.width - 20);
const y = Phaser.Math.Between(40, config.height /2 );
let enemy = enemiesGroup.get(x, y);
enemy.setInteractive()
.on('pointerdown', () => {
// 1 in 5
if(Phaser.Math.Between(1, 5) === 5){
// Drop object
this.add.rectangle(enemy.x, enemy.y, 10, 10, 0xFFFF00);
}
enemy.destroy();
})
}
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
Bonus (because I find this Phaser function especially useful):
If you want to select different loot/outcome in phaser you, could even let phaser select from a selected Array, with the function Phaser.Math.RNG.pick(...) (link to documentation)
Bonus Demo:
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
scene: {
create
},
banner: false
};
function create () {
this.add.text(10, 10, 'Click to red Boxes')
let graphics = this.make.graphics({x: 0, y: 0, add: false});
graphics.fillStyle(0xFF0000);
graphics.fillRect(0, 0, 20, 20);
graphics.generateTexture('enemy', 20, 20)
let enemiesGroup = this.add.group({
defaultKey: 'enemy',
maxSize: 10
});
let maxEnemiesToShow = 10
for(let idx = 0; idx < maxEnemiesToShow; idx++){
const x = Phaser.Math.Between(20, config.width - 20);
const y = Phaser.Math.Between(40, config.height /2 );
let enemy = enemiesGroup.get(x, y);
let loot = [0x00ff00, 0xffff00, 0x0000ff, 0x0, 0x0];
enemy
.setInteractive()
.on('pointerdown', () => {
// Select Colro from an Array of possibilities
let color = Phaser.Math.RND.pick(loot);
// only drop item if color is not black
if(color > 0){
this.add.rectangle(enemy.x, enemy.y, 10, 10, color);
}
enemy.destroy();
})
}
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
Phaser Random functions, have the added bonus that you can create your own RandomDataGenerator with a specific seed if you want, that the random numbers, that are created, are generated in the same sequence. Great for testing and so.
For a 1/5 chance, you can use JavaScript's Math.random.
Math.random() will return a float between 0 and 1.
To not hard code this, you can use a function like the following which will return true or false given an odds (in your case 1/5)
function rollRandom(odds) {
return Math.random() < odds;
}
console.log(rollRandom(1/5))

Phaser 3: Show Interactable area

The game I'm creating doesn't require any physics, however you are able to interact when hovering over/clicking on the sprite by using sprite.setInteractive({cursor: "pointer"});, sprite.on('pointermove', function(activePointer) {...}); and similar.
I ran into some issues with the interactive area and wanted to debug it by showing the "area" that is interactable. However I could only find ways to do that that are related to Arcade Physics. Is there any way to get something like a debug outline around my interactable area without Physics?
Out-Of-The-Box, without physics, I don't know any way, but one could get this function/feature with a small helper-function. (but maybe there is something, since phaser is a really extensive framework. But I also couldn't find anything).
Something like this, could do the trick, and is reuseable:
function debugSpriteArea(scene, sprite){
let debugRect = scene.add.rectangle(
sprite.x, sprite.y,
sprite.displayWidth, sprite.displayHeight,
0xff0000).setOrigin(sprite.originX,
sprite.originY);
debugRect.setDepth(-1);
}
Here the help-function in action:
let Scene = {
preload ()
{
this.load.spritesheet('brawler', 'https://labs.phaser.io/assets/animations/brawler48x48.png', { frameWidth: 48, frameHeight: 48 });
},
create ()
{
// Animation set
this.anims.create({
key: 'walk',
frames: this.anims.generateFrameNumbers('brawler', { frames: [ 0, 1, 2, 3 ] }),
frameRate: 8,
repeat: -1
});
const cody = this.add.sprite(200, 100, 'brawler')
.setOrigin(0.5);
debugSpriteArea(this, cody);
cody.play('walk');
cody.setInteractive();
this.mytext = this.add.text(10, 10, 'No Hit', { fontFamily: 'Arial' });
cody.on('pointerdown', function (pointer) {
let originXOffset = cody.displayWidth * cody.originX;
let originYOffset = cody.displayHeight * cody.originY;
let x = (pointer.x - cody.x + originXOffset ) / (cody.displayWidth / cody.width)
let y = (pointer.y - cody.y + originYOffset) / (cody.displayHeight / cody.height);
if(cody.anims && cody.anims.currentFrame){
let currentFrame = cody.anims.currentFrame;
let pixelColor = this.textures.getPixel(x, y, currentFrame.textureKey, currentFrame.textureFrame);
if(pixelColor.a > 0) {
this.mytext.text = 'hit';
} else {
this.mytext.text = 'No hit';
}
}
}, this);
}
};
function debugSpriteArea(scene, sprite){
let debugRect = scene.add.rectangle(
sprite.x, sprite.y,
sprite.displayWidth, sprite.displayHeight,
0xff0000).setOrigin(sprite.originX,
sprite.originY);
debugRect.setDepth(-1);
}
const config = {
type: Phaser.AUTO,
width: 400,
height: 200,
scene: Scene
};
const game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

Phaser 3 - How to detect if all components are sleeping?

I am new to Phaser Framework and I wanted to try making some prototype of 2D pool game from top down perspective. The problem that I have right now is detecting if all balls have stopped moving before restarting.
I use Physics.Matter and here is the source code when create so far:
this.matter.world.setBounds(0, 0, 720, 1280, 32, false, false, false, true);
this.add.image(400, 300, 'sky');
var ball = this.matter.add.image(360, 1000, 'ball');
ball.setCircle();
ball.setVelocity(-5, -20);
ball.setBounce(0.5);
for (var i = 1; i < 10; i++) {
var target = this.matter.add.image(Phaser.Math.Between(400,450), Phaser.Math.Between(400,450), 'target');
target.setCircle();
target.setVelocity(0, 0);
target.setBounce(0.7);
target.setFriction(0, 0.01);
target.setSleepEvents(true, true);
}
this.matter.world.on('sleepstart', function() {console.log('sleepstart');});
this.matter.world.on('sleepend', function() {console.log('sleepend');});
This would detect if each target has slept but I need to detect if ALL of them stopped moving. I cannot count how many has slept because sometimes when a target has entered sleep state, there is a chance some other body will bounce off it and woke it up again.
Is there any way to globally detect them?
EDIT: As a fallback plan I add a basic JS function to be called whenever update is called and count the sleeping bodies, which looks like it should not be a proper way:
var isActive = false;
// Some commands here that changes isActive = true
function onupdate() {
if (isActive) {
var bodyCount = this.matter.world.getAllBodies().filter(o => o.isSleeping === true).length;
console.log(bodyCount);
if (bodyCount >= 11) {
isActive = false;
}
}
}
I would put all objects you want to track into a phaser group (https://photonstorm.github.io/phaser3-docs/Phaser.GameObjects.Group.html) and iterate over the items in the group, to see if all have the property isSleeping set to true;
Warning: I can't say how performant this solution is, youre use case. If it is too slow, I would setup a counter variable, and count it down / up on sleepstart and sleepend. And when the counter is 0 all are sleeping.
Here a working demo, how I would do it:
(explaination are in the code, as comments)
// fix to prevent 'Warnings' in stackoverflow console
console.warn = _ => _
var config = {
type: Phaser.AUTO,
width: 400,
height: 100,
scene: { create },
physics: {
default: 'matter',
matter: {
debug: true,
setBounds: {
x: 0,
y: 0,
width: 400,
height: 100
},
enableSleeping: true
}
}
};
function create(){
// create the Phaser Group
this.targets = this.add.group();
for (var i = 1; i < 10; i++) {
var target = this.matter.add.image(200, 0, 10, 10, 'target');
target.setCircle();
target.setBounce(0.7);
target.setFriction(0, 0.01);
target.setSleepEvents(true, true);
// Add Item to the Group
this.targets.add(target);
}
this.matter.world.on('sleepstart', function(event, item){
// Check all targets are sleeping
if(!this.targets.getChildren().some( target => !target.body.isSleeping)){
console.log('all are sleeping');
}
}, this); // <- pass the scene as context
this.matter.world.on('sleepend', function() {console.log('sleepend');});
}
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

How to prevent a character to jump in midair with Matter Physics in Phaser 3?

I'm creating a game in JavaScript using the Phaser 3 framework. I'm using the Matter physics engine, and I only want the player to be able to jump (or ollie, as it is in the game) if they are touching the ground. I'm trying to use the collision detection within Matter physics, but I can't seem to get anything to work.
The error in this current code is "Uncaught TypeError: this.matter.world is not a function", although I have tried other ways of implementing the collision detection used here.
I expect the player to only be able to jump when the up arrow key is hit AND they are touching the ground.
//Configurations for the physics engine
var physicsConfig = {
default: 'matter',
matter : {
gravity: {
x: 0,
y: 2.5, // <--This is the only way I could get the skater to roll up the ramp.
},
debug: false //CHANGE THIS TO TRUE TO SEE LINES
}
}
//Variables for height and width
var gameHeight = 750;
var gameWidth = 3000;
/* Declare variable to decide whether the player can ollie or not
Player should be touching the ground or a ramp to be able to ollie */
var canOllie;
//Game configurations
var config = {
type: Phaser.AUTO,
width: 1500, //<-- this is the width of what we will see at one time
height: gameHeight,
physics: physicsConfig,
scene: {
preload: preload,
create: create,
update: update
}
}
//Start the game
var game = new Phaser.Game(config);
//Declare variables so we can access them in all functions
var skater;
var ground;
//Declare variable for the sky background
var sky;
function preload() {
//Images
this.load.image('sky', 'archery_assets/images/sky.png');
//Load sprites from TexturePacker
this.load.atlas('sheet', 'skate_assets/sprites.png', 'skate_assets/sprites.json');
//Load body shapes from PhysicsEditor
this.load.json('shapes', 'skate_assets/spritesPE.json');
}
function create() {
//Background
sky = this.add.image(1500, 325,'sky')
//Scale the image
sky.setDisplaySize(gameWidth, gameHeight);
//Get the hitboxes
var shapes = this.cache.json.get('shapes');
//Set world bounds
this.matter.world.setBounds(0, 0, gameWidth, gameHeight);
//Place ground object
ground = this.matter.add.sprite(0, 0, 'sheet', 'ground', {shape: shapes.ground});
//Ground is 600x600, so double the x pixels and we get screen width
ground.setScale(5, 1);
ground.setPosition(1500, 650);
//Let the ground detect collisions
ground.isSensor(true);
//Place the ramp
var ramp = this.matter.add.sprite(0, 0, 'sheet', 'ramp', {shape: shapes.ramp});
ramp.setPosition(550 + ramp.centerOfMass.x, 250 + ramp.centerOfMass.y);
//Create the skater
skater = this.matter.add.sprite(0, 0, 'sheet', 'roll/0001', {shape: shapes.s0001});
skater.setPosition(100 + skater.centerOfMass.x, 200 + skater.centerOfMass.y);
//Collision filtering
var staticCategory = this.matter.world.nextCategory();
ramp.setCollisionCategory(staticCategory);
ground.setCollisionCategory(staticCategory);
var skaterCategory = this.matter.world.nextCategory();
skater.setCollisionCategory(skaterCategory);
//Roll animation
//Generate the frame names
var rollFrameNames = this.anims.generateFrameNames(
'sheet', {start: 1, end: 4, zeroPad: 4,
prefix: 'roll/'}
);
//Create the animation
this.anims.create({
key: 'roll', frames: rollFrameNames, frameRate: 16, repeat: -1
});
//Push animation
var pushFrameNames = this.anims.generateFrameNames(
'sheet', {start: 5, end: 8, zeroPad: 4,
prefix: 'push/'}
);
this.anims.create({
key: 'push', frames: pushFrameNames, frameRate: 16, repeat: 0
});
//Shuvit animation
var shuvFrameNames = this.anims.generateFrameNames(
'sheet', {start: 9, end: 12, zeroPad: 4,
prefix: 'shuv/'}
);
this.anims.create({
key: 'shuv', frames: shuvFrameNames, frameRate: 32, repeat: 0
});
//Ollie animation
var ollieFrameNames = this.anims.generateFrameNames(
'sheet', {start: 13, end: 20, zeroPad: 4,
prefix: 'ollie/'}
);
this.anims.create({
key: 'ollie', frames: ollieFrameNames, frameRate: 24, repeat: 0
});
//Kickflip animation
var kfFrameNames = this.anims.generateFrameNames(
'sheet', {start: 21, end: 33, zeroPad: 4,
prefix: 'kickflip/'}
);
this.anims.create({
key: 'kickflip', frames: kfFrameNames, frameRate: 24, repeat: 0
});
//This keeps the rolling animation going once the push animation is done
skater.on('animationcomplete', () => {
skater.anims.play('roll');
});
//Input for arrowkeys
this.arrowKeys = this.input.keyboard.addKeys({
up: 'up',
down: 'down',
left: 'left',
right: 'right'
});
//Input for WASD keys
this.WASDkeys = this.input.keyboard.addKeys({
W: 'W',
A: 'A',
S: 'S',
D: 'D'
});
//Spacebar
this.spacebar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
//Camera to follow the skater
this.cameras.main.setBounds(0, 0, 3000, gameHeight);
this.cameras.main.startFollow(skater);
//Detect collision with ground
this.matter.world('collisionactive', (skater, ground) => {
if (this) {
canOllie = true;
}
else {
canOllie = false;
}
});
}
function update() {
//Set variable for player movement
var pushSpeed = 0;
var ollie = 0;
//Push
if (this.spacebar.isDown && skater.angle > -60 && skater.angle < 60) {
//Increase speed
pushSpeed = 10;
//Move player
skater.setVelocityX(pushSpeed);
//Play push animation
skater.anims.play('push');
}
//Ollie
if (Phaser.Input.Keyboard.JustDown(this.arrowKeys.up) && canOllie == true) {
//Set ollie power
ollie = -12;
//Set skate velocity
skater.setVelocityY(ollie);
//Play the ollie animation
skater.anims.play('ollie');
}
//Shuvit
if (this.arrowKeys.down.isDown) {
//Play the shuvit animation
skater.anims.play('shuv');
}
//Kickflip
if (this.WASDkeys.W.isDown) {
//Set jump height
ollie = -8
//Move the player
skater.setVelocityY(ollie);
//Play animation
skater.anims.play('kickflip');
}
//Tilting backwards in the air
if (this.arrowKeys.left.isDown && skater.y < 470) {
//Be able to turn backwards so you don't flip
skater.angle -= 3 ;
}
//Tilting forwards in the air
if (this.arrowKeys.right.isDown && skater.y < 470) {
//Be able to turn forwards so you don't flip
skater.angle += 3 ;
}
}
I have finally found the solution for this issue:
First, declare a variable called skaterTouchingGround right after the config object like so:
let skaterTouchingGround;
Second, in the create() function add the collision detector event & set the variable skaterTouchingGround to true like so:
//Detect collision with ground
this.matter.world.on("collisionactive", (skater, ground) => {
skaterTouchingGround = true;
});
Third, in the update() function & if statement, add the skaterTouchingGround variable as condition to trigger the jump & once the jump is done set the variable skaterTouchingGround to false like so:
//Ollie
if (Phaser.Input.Keyboard.JustDown(this.arrowKeys.up) && skaterTouchingGround) {
skaterTouchingGround = false;
//Set ollie power
ollie = -12;
//Set skate velocity
skater.setVelocityY(ollie);
//Play the ollie animation
skater.anims.play('ollie');
}
If you follow these steps, the skater won't be able to jump midair.
EDIT:
Finally, for your reference, here is the final full working code sample:
//Configurations for the physics engine
var physicsConfig = {
default: 'matter',
matter : {
gravity: {
x: 0,
y: 2.5, // <--This is the only way I could get the skater to roll up the ramp.
},
debug: false //CHANGE THIS TO TRUE TO SEE LINES
}
}
//Variables for height and width
var gameHeight = 750;
var gameWidth = 3000;
/* Declare variable to decide whether the player can ollie or not
Player should be touching the ground or a ramp to be able to ollie */
var canOllie;
//Game configurations
var config = {
type: Phaser.AUTO,
width: 1500, //<-- this is the width of what we will see at one time
height: gameHeight,
physics: physicsConfig,
scene: {
preload: preload,
create: create,
update: update
}
}
//Start the game
var game = new Phaser.Game(config);
//Declare variables so we can access them in all functions
var skater;
let skaterTouchingGround;
var ground;
//Declare variable for the sky background
var sky;
function preload() {
//Images
this.load.image('sky', 'archery_assets/images/sky.png');
//Load sprites from TexturePacker
this.load.atlas('sheet', 'skate_assets/sprites.png', 'skate_assets/sprites.json');
//Load body shapes from PhysicsEditor
this.load.json('shapes', 'skate_assets/spritesPE.json');
}
function create() {
//Background
sky = this.add.image(1500, 325,'sky')
//Scale the image
sky.setDisplaySize(gameWidth, gameHeight);
//Get the hitboxes
var shapes = this.cache.json.get('shapes');
//Set world bounds
this.matter.world.setBounds(0, 0, gameWidth, gameHeight);
//Place ground object
ground = this.matter.add.sprite(0, 0, 'sheet', 'ground', {shape: shapes.ground});
//Ground is 600x600, so double the x pixels and we get screen width
ground.setScale(5, 1);
ground.setPosition(1500, 650);
//Let the ground detect collisions
ground.isSensor(true);
//Place the ramp
var ramp = this.matter.add.sprite(0, 0, 'sheet', 'ramp', {shape: shapes.ramp});
ramp.setPosition(550 + ramp.centerOfMass.x, 250 + ramp.centerOfMass.y);
//Create the skater
skater = this.matter.add.sprite(0, 0, 'sheet', 'roll/0001', {shape: shapes.s0001});
skater.setPosition(100 + skater.centerOfMass.x, 200 + skater.centerOfMass.y);
//Collision filtering
var staticCategory = this.matter.world.nextCategory();
ramp.setCollisionCategory(staticCategory);
ground.setCollisionCategory(staticCategory);
var skaterCategory = this.matter.world.nextCategory();
skater.setCollisionCategory(skaterCategory);
//Roll animation
//Generate the frame names
var rollFrameNames = this.anims.generateFrameNames(
'sheet', {start: 1, end: 4, zeroPad: 4,
prefix: 'roll/'}
);
//Create the animation
this.anims.create({
key: 'roll', frames: rollFrameNames, frameRate: 16, repeat: -1
});
//Push animation
var pushFrameNames = this.anims.generateFrameNames(
'sheet', {start: 5, end: 8, zeroPad: 4,
prefix: 'push/'}
);
this.anims.create({
key: 'push', frames: pushFrameNames, frameRate: 16, repeat: 0
});
//Shuvit animation
var shuvFrameNames = this.anims.generateFrameNames(
'sheet', {start: 9, end: 12, zeroPad: 4,
prefix: 'shuv/'}
);
this.anims.create({
key: 'shuv', frames: shuvFrameNames, frameRate: 32, repeat: 0
});
//Ollie animation
var ollieFrameNames = this.anims.generateFrameNames(
'sheet', {start: 13, end: 20, zeroPad: 4,
prefix: 'ollie/'}
);
this.anims.create({
key: 'ollie', frames: ollieFrameNames, frameRate: 24, repeat: 0
});
//Kickflip animation
var kfFrameNames = this.anims.generateFrameNames(
'sheet', {start: 21, end: 33, zeroPad: 4,
prefix: 'kickflip/'}
);
this.anims.create({
key: 'kickflip', frames: kfFrameNames, frameRate: 24, repeat: 0
});
//This keeps the rolling animation going once the push animation is done
skater.on('animationcomplete', () => {
skater.anims.play('roll');
});
//Input for arrowkeys
this.arrowKeys = this.input.keyboard.addKeys({
up: 'up',
down: 'down',
left: 'left',
right: 'right'
});
//Input for WASD keys
this.WASDkeys = this.input.keyboard.addKeys({
W: 'W',
A: 'A',
S: 'S',
D: 'D'
});
//Spacebar
this.spacebar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
//Camera to follow the skater
this.cameras.main.setBounds(0, 0, 3000, gameHeight);
this.cameras.main.startFollow(skater);
//Detect collision with ground
this.matter.world.on("collisionactive", (skater, ground) => {
skaterTouchingGround = true;
});
}
function update() {
//Set variable for player movement
var pushSpeed = 0;
var ollie = 0;
//Push
if (this.spacebar.isDown && skater.angle > -60 && skater.angle < 60) {
//Increase speed
pushSpeed = 10;
//Move player
skater.setVelocityX(pushSpeed);
//Play push animation
skater.anims.play('push');
}
//Ollie
if (Phaser.Input.Keyboard.JustDown(this.arrowKeys.up) && skaterTouchingGround) {
skaterTouchingGround = false;
//Set ollie power
ollie = -12;
//Set skate velocity
skater.setVelocityY(ollie);
//Play the ollie animation
skater.anims.play('ollie');
}
//Shuvit
if (this.arrowKeys.down.isDown) {
//Play the shuvit animation
skater.anims.play('shuv');
}
//Kickflip
if (this.WASDkeys.W.isDown) {
//Set jump height
ollie = -8
//Move the player
skater.setVelocityY(ollie);
//Play animation
skater.anims.play('kickflip');
}
//Tilting backwards in the air
if (this.arrowKeys.left.isDown && skater.y < 470) {
//Be able to turn backwards so you don't flip
skater.angle -= 3 ;
}
//Tilting forwards in the air
if (this.arrowKeys.right.isDown && skater.y < 470) {
//Be able to turn forwards so you don't flip
skater.angle += 3 ;
}
}
Manuel Abascal's answer is missing a few thing. If you make skaterTouchingGround true, then you also need to make it false. What's more, you also need to check which objects are being collided. So,
this.matter.world.on("collisionactive", (e,o1, o2) => {
skaterTouchingGround = true;
});
this.matter.world.on("collisionend", (e,o1, o2) => {
skaterTouchingGround = false;
})
Where e is the event, o1 is the object 1(player) and o2 is the object 2(platform). To check which items they are, you need to label them. After you create your player, add the lines:
player.body.label = 'myLabel'
Then, in your platforms the same thing:
platform.body.label = 'myPlatform'
After that, in your collisionactive function, check the labels like so:
this.matter.world.on("collisionactive", (e,o1, o2) => {
if(o1.label == 'myLabel' && o2.label == 'myPlatform'){
skaterTouchingGround = true;
}
});
this.matter.world.on("collisionend", (e,o1, o2) => {
if(o1.label == 'myLabel' && o2.label == 'myPlatform'){
skaterTouchingGround = false;
}
})
Then:
if(skaterTouchingGround){
jump
}
The code given above works as of phaser 3, if you added your labels correctly. Do remember to change the variable names to those that you have used.
NOTE: Even if the objects are being grouped in a phaser group( this.add.group() ), when you create your sprite, you should add the label before adding it to the group using group.add()

Unable to initialize global variable in javascript based game

I have a flappy bird based clone game and I need to make a high-score feature for it. The high score disappears in a split second 'cause the game reloads and I don't know how to set the High Score as a global variable. Here is the link if you want to view it. (Warning: Lower headphone volume)
http://www.theindependentwolf.com/game/flappyWolf.html
// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'gameDiv');
// Creates a new 'main' state that will contain the game
var mainState = {
// Function called first to load all the assets
preload: function() {
// Change the background color of the game
// game.stage.backgroundColor = '#71c5cf';
//background Image
game.load.image('woods', 'woods.jpg');
// Load the bird sprite
game.load.image('bird', 'whiteWolf2.png');
// Load the pipe sprite
game.load.image('pipe', 'pipe.png');
},
// Fuction called after 'preload' to setup the game
create: function() {
// Set the physics system
game.physics.startSystem(Phaser.Physics.ARCADE);
game.add.tileSprite(0, 0, 400, 490, 'woods');
// Display the bird on the screen
this.bird = this.game.add.sprite(100, 245, 'bird');
// Add gravity to the bird to make it fall
game.physics.arcade.enable(this.bird);
this.bird.body.gravity.y = 1000;
// Call the 'jump' function when the spacekey is hit
var spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
spaceKey.onDown.add(this.jump, this);
// Create a group of 20 pipes
this.pipes = game.add.group();
this.pipes.enableBody = true;
this.pipes.createMultiple(20, 'pipe');
// Timer that calls 'addRowOfPipes' ever 1.5 seconds
this.timer = this.game.time.events.loop(1500, this.addRowOfPipes, this);
// Add a score label on the top left of the screen
this.score = 0;
this.hiScore = 0;
this.scoreLabel = this.game.add.text(20, 20, "Score: ", { font: "30px Arial", fill: "#ffffff" });
this.labelScore = this.game.add.text(120, 20, "0", { font: "30px Arial", fill: "#ffffff" });
this.hiScoreLabel = this.game.add.text(200, 20, "Hi Score: ", { font: "30px Arial", fill: "#ffffff" });
labelHiScore = this.game.add.text(340, 20, "0", { font: "30px Arial", fill: "#ffffff" });
/*
Code for the pause menu
*/
},
// This function is called 60 times per second
update: function() {
// If the bird is out of the world (too high or too low), call the 'restartGame' function
if (this.bird.inWorld == false)
this.restartGame();
// If the bird overlap any pipes, call 'restartGame'
game.physics.arcade.overlap(this.bird, this.pipes, this.restartGame, null, this);
},
// Make the bird jump
jump: function() {
// Add a vertical velocity to the bird
this.bird.body.velocity.y = -350;
},
// Restart the game
restartGame: function() {
// Start the 'main' state, which restarts the game
if(this.score > this.hiScore ){
labelHiScore.text = this.score;
}
game.state.start('main');
},
// Add a pipe on the screen
addOnePipe: function(x, y) {
// Get the first dead pipe of our group
var pipe = this.pipes.getFirstDead();
// Set the new position of the pipe
pipe.reset(x, y);
// Add velocity to the pipe to make it move left
pipe.body.velocity.x = -200;
// Kill the pipe when it's no longer visible
pipe.checkWorldBounds = true;
pipe.outOfBoundsKill = true;
},
// Add a row of 6 pipes with a hole somewhere in the middle
addRowOfPipes: function() {
var hole = Math.floor(Math.random()*5)+1;
for (var i = 0; i < 8; i++)
if (i != hole && i != hole +1)
this.addOnePipe(400, i*60+10);
this.score += 1;
this.labelScore.text = this.score;
},
};
// Add and start the 'main' state to start the game
game.state.add('main', mainState);
// document.getElementById("#startButton").onclick(function(){
// alert("Hi");
labelHiScore = 0;
game.state.start('main');
// });
Try with following changes:
In restartGame method:
restartGame: function() {
if(this.score > localStorage.getItem("hiScore") ){
localStorage.setItem("hiScore", this.score);
this.labelHiScore.text = localStorage.getItem("hiScore");
}
game.state.start('main');
},
In "labelHiScore" varaible Declaration:
this.labelHiScore = this.game.add.text(340, 20, ("hiScore" in localStorage ? localStorage.getItem("hiScore") : "0"), { font: "30px Arial", fill: "#ffffff" });
I hope you got what is the problem, in short
In restartGame method you are trying to assign score to window scoped variable instead of functional scope.
Adding "this." will make to find variable in current object.
Also added score to local storage to preserve highscore, and when the game is reloaded picking value from local storage.

Categories