phaser 3 Trying to make bullet travel towards a location - javascript

i am trying to make my bullet travel towards the cursor location. I have tried lots of things and I just can't get it to work. I have the player arm set up to always move to the player shoulder level. The player's arm and the gun has the same rotation value. The rotation value is calculated using Phaser.Math.Angle.BetweenPoints(playerArm, player1Aim);. I found a couple examples but i couldn't get them to work. Please teach me how to use it. I am a newbie. Please help. Here is my code:
var config = {
type: Phaser.AUTO,
width: 512,
height: 512,
physics: {
default: 'arcade',
arcade: {
gravity: {
y: 1500
},
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
// plugins: {
// global: [{
// key: 'PhaserPauseRenderPlugin',
// plugin: PhaserPauseRenderPlugin,
// mapping: 'render'
// }]
// }
};
// class SceneMain extends Phaser.Scene {
// constructor() {
// super('SceneMain');
// }
// preload() {}
// create() {
// //make 3 bars
// let healthBar = this.makeBar(140, 100, 0x2ecc71);
// this.setValue(healthBar, 100);
// // let powerBar = this.makeBar(140, 200, 0xe74c3c);
// // this.setValue(powerBar, 50);
// // let magicBar = this.makeBar(140, 300, 0x2980b9);
// // this.setValue(magicBar, 33);
// }
// makeBar(x, y, color) {
// //draw the bar
// let bar = this.add.graphics();
// //color the bar
// bar.fillStyle(color, 1);
// //fill the bar with a rectangle
// bar.fillRect(0, 0, 200, 50);
// //position the bar
// bar.x = x;
// bar.y = y;
// //return the bar
// return bar;
// }
// setValue(bar, percentage) {
// //scale the bar
// bar.scaleX = percentage / 100;
// }
// update() {}
// }
var player;
var platforms;
var cursors;
var gameOver = false;
var score = 0;
var time;
var waves;
var enemies;
var enemy;
var health;
var hacking = false;
var timer;
var enemyCount = 0;
var startGame = false;
var timeSpeed = 1;
var keys;
var damageStrike = 0;
var toMouse = 0;
var toPlayer = 0;
var bullets;
var ship;
var speed;
var stats;
var cursors;
var lastFired = 0;
var fire = false;
var pointerDown = false;
// var healthBar = new SceneMain();
// spaceBar input
// var spaceBar = Phaser.Input.Keyboard.KeyCodes.SPACE;
var game = new Phaser.Game(config);
function preload() {
//this.load.image('platform', 'images/platform.png');
// this.load.image('background', 'images/background.png');z
this.load.image('background', 'images/background.png');
this.load.image('platform', 'images/platform.png');
this.load.image('longPlatform', 'images/platform long.png');
this.load.image('itembg', 'images/item bg.png');
this.load.image('playerArm', 'images/player arm.png');
this.load.image('enemyArm', 'images/enemy arm.png');
this.load.image('playerGun', 'images/player gun.png');
this.load.image('enemyGun', 'images/enemy gun.png');
this.load.image('medkit', 'images/medkit.png');
this.load.image('aim', 'images/aim.png');
this.load.image('bullet', 'images/laser.png');
this.load.spritesheet('player', 'images/player idle-1.png', {
frameWidth: 49,
frameHeight: 128
});
this.load.spritesheet('enemy', 'images/enemy.png', {
frameWidth: 49,
frameHeight: 128
});
}
function create() {
// var Bullet = new Phaser.Class({
// Extends: Phaser.GameObjects.Image,
// initialize:
// // Bullet Constructor
// function Bullet(scene) {
// Phaser.GameObjects.Image.call(this, scene, 0, 0, 'bullet');
// this.speed = 1;
// this.born = 0;
// this.direction = 0;
// this.xSpeed = 0;
// this.ySpeed = 0;
// this.setSize(12, 12, true);
// },
// // Fires a bullet from the player to the reticle
// fire: function(player, target) {
// this.setPosition(player.x, player.y); // Initial position
// this.direction = Math.atan((target.x - this.x) / (target.y - this.y));
// // Calculate X and y velocity of bullet to moves it from shooter to target
// if (target.y >= this.y) {
// this.xSpeed = this.speed * Math.sin(this.direction);
// this.ySpeed = this.speed * Math.cos(this.direction);
// } else {
// this.xSpeed = -this.speed * Math.sin(this.direction);
// this.ySpeed = -this.speed * Math.cos(this.direction);
// }
// this.rotation = player.rotation; // angle bullet with shooters rotation
// this.born = 0; // Time since new bullet spawned
// },
// // Updates the position of the bullet each cycle
// update: function(time, delta) {
// this.x += this.xSpeed * delta;
// this.y += this.ySpeed * delta;
// this.born += delta;
// if (this.born > 500) {
// this.setActive(false);
// this.setVisible(false);
// }
// }
// });
// playerBullets = this.physics.add.group({
// classType: Bullet,
// runChildUpdate: true
// });
speed = Phaser.Math.GetSpeed(300, 1);
// healthBar.makeBar(32, 32, 0xffffff);
// console.log(timer);
// add background
// this.add.image(256, 256, 'background');
background = this.add.image(256, 256, 'background');
background.alpha = 0.8;
itemBg = this.add.image(256, 520, 'itembg')
platforms = this.physics.add.staticGroup();
// Here we create the ground.
platforms.create(256, 450, 'longPlatform').refreshBody();;
// platforms.create(256, 450, 'platform');
platforms.create(50, 175, 'platform');
platforms.create(460, 175, 'platform');
platforms.create(50, 350, 'platform');
platforms.create(460, 350, 'platform');
platforms.create(265, 250, 'platform');
player = this.physics.add.sprite(256, 10, 'player');
player.setScale(0.5);
player.setBounce(0.1);
player.setCollideWorldBounds(true);
playerArm = this.add.image(256, 256, 'playerArm');
playerArm.setScale(0.5);
playerArm.angle = 0;
playerGun = this.add.image(256, 256, 'playerGun');
playerGun.setScale(0.5);
playerGun.angle = 0;
enemyArm = this.add.image(256, 256, 'enemyArm');
enemyArm.setScale(0.5);
enemyArm.angle = 0;
enemyGun = this.add.image(256, 256, 'enemyGun');
enemyGun.setScale(0.5);
enemyGun.angle = 0;
player1Aim = this.add.image(256, 256, 'aim');
player1Aim.setScale(2);
player1Aim.angle = 0;
bullet = this.add.image(256, 10, 'bullet');
bullet.setScale(0.25);
bullet.angle = 0;
var playerX = player.x;
var playerY = player.y;
enemies = this.physics.add.group();
medkits = this.physics.add.group();
spawn = (x, enemyName) => {
enemyPlayer = this.physics.add.sprite(x, 20, enemyName);
// enemyPlayer = this.physics.add.sprite.destroy(true);
console.log(enemyPlayer);
enemyPlayer.setScale(0.5);
enemyPlayer.setBounce(0.1);
enemyPlayer.setCollideWorldBounds(true);
enemyPlayer.allowGravity = true;
return enemyPlayer;
}
spawnMedkit = (x, enemyName) => {
enemyPlayer = this.physics.add.sprite(x, 20, enemyName);
// enemyPlayer = this.physics.add.sprite.destroy(true);
console.log(enemyPlayer);
enemyPlayer.setScale(1);
enemyPlayer.setBounce(0.1);
enemyPlayer.setCollideWorldBounds(true);
enemyPlayer.allowGravity = true;
return enemyPlayer;
}
enemy = spawn(450, 'enemy');
medkit = spawnMedkit(100, 'medkit');
enemyCount += 1;
console.log(enemyCount);
// enemy = enemies.create(450, 20, 'enemy')
// // enemies.create(250, 20, 'enemy')
// enemy.setScale(0.5)
// enemy.setBounce(0.1);
// enemy.setCollideWorldBounds(true);
// enemy.allowGravity = true;
cursors = this.input.keyboard.createCursorKeys();
this.physics.add.collider(player, platforms);
this.physics.add.collider(enemy, platforms);
this.physics.add.collider(medkit, platforms);
// this.physics.add.collider(bombs, platforms);
health = 100;
waves = 0;
// timer = this.time.create(false);
// The score
scoreText = this.add.text(16, 16, 'score: 0', {
fontSize: '25px',
fill: '#00FFFF'
});
// FPS
fps = this.add.text(16, 50, game.loop.actualFps, {
fontSize: '15px',
fill: '#00FFFF'
});
timeScale = this.add.text(16, 70, this.physics.world.timeScale, {
fontSize: '15px',
fill: '#00FFFF'
});
gunRotation = this.add.text(16, 100, 'gun rotation: 0', {
fontSize: '15px',
fill: '#00FFFF'
});
// gameStatus = this.add.text(16, 60, 'Game Status: Alive', {
// fontSize: '25px',
// fill: '#00FFFF'
// });
// hp = this.add.text(16, 100, 'Health: ' + health, {
// fontSize: '25px',
// fill: '#00FFFF'
// });
// add collisions
this.physics.add.collider(player, enemy, damage, null, this);
this.physics.add.collider(player, medkit, healByMedkit, null, this);
// this.physics.add.collider(laser, enemy, hit, null, this);
keys = this.input.keyboard.addKeys('W,A,S,D,F,J,K,L,SPACE');
var r1 = this.add.rectangle(playerX, playerY - 15, 200, 69, 10, 0x6666ff);
this.input.on('pointermove', function(pointer) {
toMouse = Phaser.Math.Angle.BetweenPoints(playerArm, player1Aim);
});
this.input.on('pointerdown', function(pointer) {
// shoot the bullet towards the cursor (player1Aim)
});
startGame = true;
}
function update(time, delta) {
var playerX = player.x;
var playerY = player.y;
var enemyX = enemy.x;
var enemyY = enemy.y;
var playerArmX = playerArm.x;
var playerArmY = playerArm.y;
var playerArmRotation = playerArm.angle;
var mouseX = game.input.mousePointer.x;
var mouseY = game.input.mousePointer.y;
// var theta =
// console.log(playerArmRotation);
// position the arm to the shoulder level of the player
playerArm.x = playerX;
playerArm.y = playerY - 5;
playerGun.x = playerX;
playerGun.y = playerY - 3;
enemyArm.x = enemyX;
enemyArm.y = enemyY - 5;
enemyGun.x = enemyX;
enemyGun.y = enemyY - 5;
player1Aim.x = mouseX;
player1Aim.y = mouseY;
toPlayer = Phaser.Math.Angle.BetweenPoints(enemy, player);
playerArm.rotation = Phaser.Math.Angle.BetweenPoints(playerArm, player1Aim);
playerGun.rotation = Phaser.Math.Angle.BetweenPoints(playerArm, player1Aim);
enemyArm.rotation = toPlayer;
enemyGun.rotation = toPlayer;
// rotate gun for player
if (playerGun.angle >= 90 || playerGun.angle <= -90) {
playerGun.flipY = true;
// console.log('flipped')
} else {
playerGun.flipY = false;
}
// rotate gun for player
if (enemyGun.angle >= 90 || enemyGun.angle <= -90) {
enemyGun.flipY = true;
// console.log('flipped')
} else {
enemyGun.flipY = false;
}
// this.input.on('pointerdown', function(pointer) {
// if (pointerDown == false) {
// pointerDown = true;
// fire();
// console.log('FIRE');
// } else {
// pointerDown = false;
// }
// });
// this.input.on('pointerdown', function(pointer, time, lastFired) {
// if (player.active === false)
// return;
// // Get bullet from bullets group
// var bullet = playerBullets.get().setActive(true).setVisible(true);
// if (bullet) {
// bullet.fire(playerGun, player1Aim);
// // this.physics.add.collider(enemy, bullet, enemyHitCallback);
// }
// }, this);
// this.input.on('pointerdown', function(pointer) {
// if (time > lastFired) {
// var bullet = bullets.get();
// console.log('test2');
// if (bullet) {
// // bullet.rotation = playerGun.rotation;
// bullet.fire(playerGun.x, playerGun.y);
// lastFired = time + 50;
// }
// }
// });
if (startGame == true) {
if (keys.J.isDown) {
this.physics.world.timeScale = 1.75;
// console.log(this.physics.world.timeScale);
// timeSpeed = 0.5;
// console.log(timeSpeed);
} else
if (keys.K.isDown) {
this.physics.world.timeScale = 0.75;
// timeSpeed = 1;
}
if (keys.L.isDown) {
}
if (gameOver) {
return;
gameStatus.setText('Game Status: Dead')
}
if (cursors.left.isDown || keys.A.isDown) {
player.setVelocityX(-160 * timeSpeed);
} else if (cursors.right.isDown || keys.D.isDown) {
player.setVelocityX(160 * timeSpeed);
} else {
player.setVelocityX(0 * timeSpeed);
}
if (cursors.up.isDown && player.body.touching.down) {
player.setVelocityY(-650 * timeSpeed);
}
if (keys.W.isDown && player.body.touching.down) {
player.setVelocityY(-650 * timeSpeed);
}
if (keys.SPACE.isDown && player.body.touching.down) {
player.setVelocityY(-650 * timeSpeed);
}
if (waves == 0) {
waves += 1;
console.log(waves)
}
fps.setText('fps: ' + game.loop.actualFps);
scoreText.setText('Score: ' + score);
timeScale.setText('timeScale: ' + this.physics.world.timeScale);
gunRotation.setText('gun rotation: ' + playerGun.angle);
}
}
function damage(player, enemy) {
enemy.disableBody(true, true);
// enemy.body.enable = false;
// enemy.body.gameObject.active = false;
enemyCount -= 1;
console.log(enemyCount);
health -= 10;
score -= 10;
damageStrike += 1;
if (enemyCount === 0) {
var randomX = Phaser.Math.FloatBetween(0, 500);
enemy.enableBody(true, randomX, 15, true, true);
enemyCount += 1;
console.log(enemyCount);
}
if (damageStrike === 3 && medkits.countActive(false) == 0) {
var randomX = Phaser.Math.FloatBetween(0, 500);
medkit.enableBody(true, randomX, 15, true, true);
damageStrike = 0;
}
console.log('Health: ' + health);
if (health <= 0) {
gameOver = true;
}
}
function hit(laser, enemy) {
score += 10;
enemy.disableBody(true, true);
}
function healByMedkit(player, medkit) {
score += 5;
health += 15;
console.log(health);
medkit.disableBody(true, true);
}

Well if you want to rotate a gameObjects and shoot something in a specific angle, in Phaser you should have to keep somethings in mind:
Origin of the gameObject (since the rotation occurs around this point)
The direction / angle offset of the gameObject you want to rotate
Apart from that, everything is more or less straightforward, calculate the vector for "shooting" a bullet and set the velocity of that bullet.
Here a short demo:
In this Demo, the both main factors are shown, origin and "angle-offset".
(It should cover the basic from your code)
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
physics: {
default: 'arcade',
arcade: {
gravity:{ y: 50 },
}
},
scene: {
create,
update
},
banner: false
};
function create () {
this.add.text(10, 10, 'Click to shoot bullets')
.setOrigin(0);
// head
this.add.circle ( 42, 60, 8, 0xffffff)
.setOrigin(0);
// body
let player = this.add.rectangle( 40, 80, 20, 50, 0xffffff)
.setOrigin(0);
// sholder
this.add.circle ( 50, 90, 5, 0xff0000)
.setOrigin(0.5);
// arm
let playerArm = this.add.rectangle( 50, 90, 10, 30, 0xff0000)
// Point #1: the Point of rotation is more or less the shoulder
.setOrigin(.5, 0)
.setDepth(10);
// create bullet Group
this.bullets = this.add.group();
this.input.on('pointermove', pointer => {
let rotation = Phaser.Math.Angle.BetweenPoints(playerArm, pointer);
// Point #2: Angle-Offset since the 0 Degrees is on the right,
// and the arm is pointing down I need to subtract 90° 0 PI/2
playerArm.rotation = rotation - Math.PI / 2;
});
this.input.on('pointerdown', pointer => {
let speed = 300;
// create bullet
let bullet = this.add.circle( playerArm.x, playerArm.y, 4, 0xffff00)
.setDepth(9);
this.physics.add.existing(bullet);
// get Vector where to shoot bullet
let vector = new Phaser.Math.Vector2( pointer.x - playerArm.x, pointer.y - playerArm.y );
// set Speed of bullet
vector.setLength(speed);
// DEMO: to shoot in a straightline, just comment the following line in
// bullet.body.setAllowGravity(false);
// DEMO: QuickFix to destroy the bullet after 1 Second automatically
// setTimeout( () => bullet.destroy(), 1000);
// add bullet to group
this.bullets.add(bullet);
bullet.body.setVelocity(vector.x, vector.y);
});
}
function update(){
this.bullets.getChildren().forEach(bullet => {
if(bullet.x > config.width){
bullet.destroy();
}
})
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
If you want the bullet to fly without gravity / in a straight line, just add this line bullet.body.setAllowGravity(false); after the creation of the bullet, to turn off the physics effect for the bullet.

Related

Javascript - 2d Platformer - Bounding Box Collision Detection

I am trying to make a sonic 2d platformer. However I am struggling with making my sonic entity collide with my platform. Right now my sonic is falling through the platform as if my collisionCheck() method does not work at all.
Here is my sonic.js:
class Sonic {
constructor(game) {
this.game = game;
this.game.sonic = this; // special entity
this.position = {
x: 0,
y: 0
}
this.velocity = {
x: 0, //increase as to the right ->
y: 0 // increase as downwards
}
this.speed = 1300;
this.jumpSpeed = 200;
this.spinSpeed = 1400;
this.spritesheet = ASSET_MANAGER.getAsset("./sprites/realSonicSheet.png");
this.updateBB();
this.animations = [];
this.state = 0;
this.direction = 0;
this.loadAnimations();
this.ground = 550;
this.onGround = false;
this.BB = null;
this.lastBB = null;
}
loadAnimations() {
for (var i = 0; i < 4; i++) { // four states (idle, running, jumping and spinning)
this.animations.push([]);
for (var k = 0; k < 2; k++) { // two directions (right or left)
this.animations[i].push([]);
}
}
// idle animation for state = 0
// facing right = 0
this.animations[0][0] = new Animator(this.spritesheet, 5, 723, 45, 45, 1, 0.33, 0, false, true);
// facing left = 1
this.animations[0][1] = new Animator(this.spritesheet, 741, 38, -41, 47, 1, 0.33, 0, true, true); // change to true true if issues
// run animation
// facing right
this.animations[1][0]= new Animator(this.spritesheet, 2, 916, 49, 45, 14, 0.08, 0, false, true);
// facing left
this.animations[1][1] = new Animator(this.spritesheet, 745, 230, -49, 47, 14, 0.08, 0, false, true);
// jump animation
// facing right
this.animations[2][0] = new Animator(this.spritesheet, 340, 1160, 47, 56, 8, 0.08, 0, false, true);
// facing left
this.animations[2][1] = new Animator(this.spritesheet, 410, 480, -47, 56, 8, 0.08, 0, false, true);
// spinning animation
// facing right
this.animations[3][0] = new Animator(this.spritesheet, 1, 1113, 47, 40, 10, 0.08, 0, false, true);
// facing left
this.animations[3][1] = new Animator(this.spritesheet, 746, 427, -47, 40, 10, 0.08, 0, false, true);
}
updateBB() {
this.BB = new BoundingBox(this.position.x, this.position.y, 155, 130, "red");
this.lastBB = new BoundingBox(this.BB.x, this.BB.y, this.BB.width, this.BB.height, this.BB.color);
console.log("This is this.BB", this.BB);
}
update() {
const GRAVITY = 0.5;
this.updateBB();
let standingOnPlatform = false;
let canvasHeight = 768;
// Move left
if (this.game.left) {
console.log(this.game.left);
this.position.x -= this.speed * this.game.clockTick;
this.direction = 1;
this.state = 1;
console.log(this.position.x);
}
// Move right and spinning left
if (this.game.spin && this.game.left) {
this.position.x -= this.spinSpeed * this.game.clockTick;
this.state = 3;
}
// Move right
if (this.game.right) {
console.log(this.game.right);
this.position.x += this.speed * this.game.clockTick;
this.direction = 0;
this.state = 1
console.log(this.position.x)
}
// Jump
if (this.game.jump) {
console.log(this.game.jump)
this.position.y -= 20;
this.state = 2;
this.direction = 0;
}
this.velocity.y += GRAVITY; // Gravity to pull sonic down after jumping
this.position.y += this.velocity.y;
// Spin
if (this.game.spin) {
console.log(this.game.spin)
this.position.x += this.spinSpeed * this.game.clockTick;
this.position.y += 10;
this.state = 3;
}
// Set state back to idle if no actions are being performed
if (!this.game.left && !this.game.right && !this.game.jump && !this.game.spin) {
this.state = 0;
}
// If Sonic is not standing on a platform, check if he has fallen off the screen
if (!standingOnPlatform) {
this.velocity.y += GRAVITY;
this.position.y += this.velocity.y;
// // Check if Sonic has fallen off the screen
// if (this.position.y > canvasHeight) {
// // Reload the game
// window.location.reload();
// this.position.y = 300; // start at y position 300
// }
}
// Update the bounding box for Sonic's new position
this.updateBB();
this.collisionCheck();
}
collisionCheck() {
this.game.entities.forEach(entity => {
if (this !== entity && entity.BB && this.BB.collide(entity.BB)) {
if (entity instanceof Platform) {
if (this.velocity.y > 0 && this.lastBB.bottom <= entity.BB.top) {
this.position.y = entity.BB.top - this.BB.height;
this.velocity.y = 0;
this.onGround = true;
return;
}
if (this.velocity.y < 0 && this.lastBB.top >= entity.BB.bottom) {
this.position.y = entity.BB.bottom;
this.velocity.y = 0;
return;
}
if (this.velocity.x > 0 && this.lastBB.right <= entity.BB.left) {
this.position.x = entity.BB.left - this.BB.width;
this.velocity.x = 0;
return;
}
if (this.velocity.x < 0 && this.lastBB.left >= entity.BB.right) {
this.position.x = entity.BB.right;
this.velocity.x = 0;
return;
}
}
}
});
}
draw(ctx) {
if(this.state < 0 || this.state > 3) this.state = 0;
let done = this.animations[this.state][this.direction].drawFrame(this.game.clockTick, ctx, this.position.x - this.game.camera.x , this.position.y);
if (done) {
this.animations[this.state][this.direction].elapsedTime = 0;
this.state = 0;
}
if (PARAMS.DEBUG) {
this.game.ctx.strokeStyle = "red";
this.game.ctx.strokeRect(this.BB.x - this.game.camera.x, this.BB.y, this.BB.width, this.BB.height);
}
}
}
Here is my platform.js
class Platform {
constructor(game, x, y, width, height) {
this.game = game;
this.position = {
x: x,
y: y
};
this.width = width;
this.height = height;
this.boundingBox = {
x: this.position.x,
y: this.position.y,
width: this.width,
height: this.height
};
this.spritesheet = ASSET_MANAGER.getAsset("./sprites/floor.png");
}
updateBB() {
this.boundingBox.x = this.position.x;
this.boundingBox.y = this.position.y;
}
update() {
this.updateBB();
}
draw(ctx) {
ctx.drawImage(this.spritesheet, this.position.x - this.game.camera.x, this.position.y, this.width, this.height);
if (PARAMS.DEBUG) {
ctx.strokeStyle = "lime";
ctx.strokeRect(
this.boundingBox.x - this.game.camera.x,
this.boundingBox.y,
this.boundingBox.width,
this.boundingBox.height
);
}
}
}
I have tried debugging my collisionCheck method (line 142 of sonic.js)and seeing if my bounding boxes are drawn correctly around my sonic and platforms and they are drawn correctly.

Draw moving line in phaser 3

I want to draw line, where it's first pair of coordinates situated in the center of drew circle and it's second pair will be unsettled until I direct it to the cirlce with the same color, which have first one. Do you have any ideas?
My code:
let config = {
type: Phaser.AUTO,
width: 800,
height: 600,
backgroundColor: '#f0ebeb',
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
},
scale: {
autoCenter: Phaser.Scale.CENTER_BOTH
}
};
let game = new Phaser.Game(config);
let items = [];
let dots = new Map([
[1, '#4293f5'],
[2, '#42f554'],
[3, '#f5e942'],
[4, '#f55a42'],
[5, '#f542c8'],
])
function preload() {
}
function create() {
let x = 100;
let y = 0;
for (i = 0; i < 36; i++) {
if (i % 6 === 0) {
y += 85;
x = 100;
}
this.add.circle(x, y, 35, parseInt(dots.get(getRandomInt(5)).replace(/^#/, ''), 16));
x += 125;
}
}
function update() { }
function getRandomInt(max) {
return Math.floor(Math.random() * max) + 1;
}
What I am trying to do: https://play.google.com/store/apps/details?id=com.nerdyoctopus.gamedots
A quick possible solution could be to use the pointer Events (pointerdown, pointermove and pointerup) of the scene. Here is a demo code, with the basic functionality
let config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 400,
height: 200,
scene: { create }
};
let game = new Phaser.Game(config);
let isDragging = false;
let lineStartPosition = {x:0 , y:0};
let line;
function create ()
{
let cicles = []
for(let rowIdx = 0; rowIdx < 4; rowIdx++ ){
for(let colIdx = 0; colIdx < 2; colIdx++ ){
let circle = this.add.circle(50 + 100 * rowIdx, 50 + 100 * colIdx, 25, 0x6666ff).setOrigin(.5);
circle.setInteractive();
cicles.push(circle);
}
}
line = this.add.line(0,0, 0,0, 100, 100, 0xffffff).setOrigin(0);
line.setLineWidth(5);
line.visible = false;
// adding the events to the scene
this.input.on('pointerdown', dragStart);
this.input.on('pointerup', dragEnd);
this.input.on('pointermove', drag);
}
function dragStart(pointer, gameObjects){
if(gameObjects.length == 0)
return
lineStartPosition.x = gameObjects[0].x;
lineStartPosition.y = gameObjects[0].y;
isDragging = true;
line.x = gameObjects[0].x;
line.y = gameObjects[0].y;
line.setTo(0, 0, 0, 0);
line.visible = true;
}
function drag(pointer, gameObject){
if(isDragging == true){
line.setTo(0, 0, pointer.x - lineStartPosition.x, pointer.y - lineStartPosition.y);
}
}
function dragEnd(pointer, gameObject){
isDragging = false;
}
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

How do I add a rectangle to the zoomed canvas area?

I'm using Fabric JS. Every time I press the Add Door button it creates on the upper left. I gave the values ​​in the rectangle (left: 40, top: 40,).
However, when I press the button while I am on the area I zoomed, I want it to add it to the area I zoomed. I looked at a few examples but could not find what I wanted. How can I do that?
Video
var canvas = new fabric.Canvas('c');
canvas.setBackgroundImage('https://i.hizliresim.com/0pIPiv.jpg', canvas.renderAll.bind(canvas));
var uniqids = 0;
$("#door").on("click", function(e) {
rect = new fabric.Rect({
id:uniqid,
left: 40,
top: 40,
width: 35,
height: 50,
fill: 'blue',
stroke: 'blue',
strokeWidth: 5,
strokeUniform: false,
hasControls : true,
});
var uniqid = uniqids.toString();
var text = new fabric.Text(uniqid, {
fontSize: 30,
originX: 'center',
originY: 'right'
});
var group = new fabric.Group([ rect, text ], {
left: 0,
top: 100,
});
canvas.add(group);
uniqids++;
canvas.on('selection:cleared', c => {
console.log("empty");
});
canvas.selection = false;
});
//*****************************
// canvas.on('mouse:wheel', function(opt) {
// var delta = opt.e.deltaY;
// var zoom = canvas.getZoom();
// zoom *= 0.999 ** delta;
// if (zoom > 20) zoom = 20;
// if (zoom < 0.01) zoom = 0.01;
// canvas.setZoom(zoom);
// opt.e.preventDefault();
// opt.e.stopPropagation();
// })
$('#getid').click(function() {
var activeObject = canvas.getActiveObjects();
alert(canvas.getActiveObject().id);
});
//***************************************
$("#save").on("click", function(e) {
$(".save").html(canvas.toSVG());
});
$('#delete').click(function() {
var activeObject = canvas.getActiveObjects();
canvas.discardActiveObject();
canvas.remove(...activeObject);
});
$("#btnResetZoom").on("click", function(e) {
canvas.setViewportTransform([1,0,0,1,0,0]);
});
canvas.on('mouse:wheel', function(opt) {
var delta = opt.e.deltaY;
var zoom = canvas.getZoom();
zoom *= 0.999 ** delta;
if (zoom > 20) zoom = 20;
if (zoom < 1) zoom = 1;
canvas.zoomToPoint({x: opt.e.offsetX, y: opt.e.offsetY}, zoom);
opt.e.preventDefault();
opt.e.stopPropagation();
});
var shiftKeyDown = true;
var mouseDownPoint = null;
canvas.on('mouse:move', function(options) {
if (shiftKeyDown && mouseDownPoint) {
var pointer = canvas.getPointer(options.e, true);
var mouseMovePoint = new fabric.Point(pointer.x, pointer.y);
canvas.relativePan(mouseMovePoint.subtract(mouseDownPoint));
mouseDownPoint = mouseMovePoint;
keepPositionInBounds(canvas);
}
});
var Direction = {
LEFT: 0,
UP: 1,
RIGHT: 2,
DOWN: 3
};
var zoomLevel = 0;
var zoomLevelMin = 0;
var zoomLevelMax = 3;
var shiftKeyDown = false;
var mouseDownPoint = null;
canvas.on('mouse:down', function(options) {
var pointer = canvas.getPointer(options.e, true);
mouseDownPoint = new fabric.Point(pointer.x, pointer.y);
});
canvas.on('mouse:up', function(options) {
mouseDownPoint = null;
});
canvas.on('mouse:move', function(options) {
if (shiftKeyDown && mouseDownPoint) {
var pointer = canvas.getPointer(options.e, true);
var mouseMovePoint = new fabric.Point(pointer.x, pointer.y);
canvas.relativePan(mouseMovePoint.subtract(mouseDownPoint));
mouseDownPoint = mouseMovePoint;
keepPositionInBounds(canvas);
}
});
fabric.util.addListener(document.body, 'keydown', function(options) {
if (options.repeat) {
return;
}
var key = options.which || options.keyCode; // key detection
if (key == 16) { // handle Shift key
canvas.defaultCursor = 'move';
canvas.selection = false;
shiftKeyDown = true;
} else if (key === 37) { // handle Left key
move(Direction.LEFT);
} else if (key === 38) { // handle Up key
move(Direction.UP);
} else if (key === 39) { // handle Right key
move(Direction.RIGHT);
} else if (key === 40) { // handle Down key
move(Direction.DOWN);
}
});
fabric.util.addListener(document.body, 'keyup', function(options) {
var key = options.which || options.keyCode; // key detection
if (key == 16) { // handle Shift key
canvas.defaultCursor = 'default';
canvas.selection = true;
shiftKeyDown = false;
}
});
// jQuery('.canvas-container').on('mousewheel', function(options) {
// var delta = options.originalEvent.wheelDelta;
// if (delta != 0) {
// var pointer = canvas.getPointer(options.e, true);
// var point = new fabric.Point(pointer.x, pointer.y);
// if (delta > 0) {
// zoomIn(point);
// } else if (delta < 0) {
// zoomOut(point);
// }
// }
// });
function move(direction) {
switch (direction) {
case Direction.LEFT:
canvas.relativePan(new fabric.Point(-10 * canvas.getZoom(), 0));
break;
case Direction.UP:
canvas.relativePan(new fabric.Point(0, -10 * canvas.getZoom()));
break;
case Direction.RIGHT:
canvas.relativePan(new fabric.Point(10 * canvas.getZoom(), 0));
break;
case Direction.DOWN:
canvas.relativePan(new fabric.Point(0, 10 * canvas.getZoom()));
break;
}
keepPositionInBounds(canvas);
}
// function zoomIn(point) {
// if (zoomLevel < zoomLevelMax) {
// zoomLevel++;
// canvas.zoomToPoint(point, Math.pow(2, zoomLevel));
// keepPositionInBounds(canvas);
// }
// }
// function zoomOut(point) {
// console.log(zoomLevel, zoomLevelMin);
// if (zoomLevel > zoomLevelMin) {
// zoomLevel--;
// canvas.zoomToPoint(point, Math.pow(2, zoomLevel));
// keepPositionInBounds(canvas);
// }
// }
function keepPositionInBounds() {
var zoom = canvas.getZoom();
var xMin = (2 - zoom) * canvas.getWidth() / 2;
var xMax = zoom * canvas.getWidth() / 2;
var yMin = (2 - zoom) * canvas.getHeight() / 2;
var yMax = zoom * canvas.getHeight() / 2;
var point = new fabric.Point(canvas.getWidth() / 2, canvas.getHeight() / 2);
var center = fabric.util.transformPoint(point, canvas.viewportTransform);
var clampedCenterX = clamp(center.x, xMin, xMax);
var clampedCenterY = clamp(center.y, yMin, yMax);
var diffX = clampedCenterX - center.x;
var diffY = clampedCenterY - center.y;
if (diffX != 0 || diffY != 0) {
canvas.relativePan(new fabric.Point(diffX, diffY));
}
}
function clamp(value, min, max) {
return Math.max(min, Math.min(value, max));
}
#c {
background-color: grey;
margin-top: 10px;
}
button {
padding: 10px 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.1.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="door">Door</button>
<button id="delete">Delete Door</button>
<button id="save">Save</button>
<button id="getid">GET ID</button>
<button id="btnResetZoom">Reset Zoom</button>
<canvas id="c" width="800" height="800"></canvas>
<br>
<p class="save">
</p>
I think you should use the transformPoint method to translate position
$("#door").on("click", function (e) {
const points = {};
const iVpt = fabric.util.invertTransform(canvas.viewportTransform);
points.tl = fabric.util.transformPoint({x: 40, y: 40}, iVpt);
rect = new fabric.Rect({
id: uniqid,
left: points.tl.x,
top: points.tl.y,
width: 35,
height: 50,
fill: "blue",
stroke: "blue",
strokeWidth: 5,
strokeUniform: false,
hasControls: true,
});

Video Game Score Issues

Currently I am creating a Javascript game. I have successfully created all the game pieces and how my game's basic functions should work. However, I am having 2 issues that I can't seem to solve, and I've looked for a few weeks now trying to figure out how to do it. I can't figure out how to get the game to result in a gameover if my player gets pushed of falls off screen. Also, I am unsure on how I can get the score to continously increase for as long as the player is still "alive". If anyone can either demonstrate how to do these things or point me in the direction of a tutorial or article on how to do it it would be very helpful.
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
const seeded = (() => {
var seed = 1;
return {
max: 2576436549074795,
reseed(s) {
seed = s
},
random() {
return seed = ((8765432352450986 * seed) + 8507698654323524) % this.max
},
}
})();
const randSeed = (seed) => seeded.reseed(seed);
const randSI = (min, max = min + (min = 0)) => (seeded.random() % (max - min)) + min;
const randS = (min, max = min + (min = 0)) => (seeded.random() / seeded.max) * (max - min) + min;
randSeed(100); // seed the random generators
function Player(color, keymap, x) {
this.x = (typeof x === 'undefined') ? 1 : x;
this.y = 7;
this.width = 15;
this.height = 15;
this.speed = 10;
this.velX = 0;
this.velY = 0;
this.jumping = false;
this.keymap = {}
for (let key in keymap) {
switch (keymap[key]) {
case 'jump':
this.keymap[key] = this.jump
break;
case 'left':
this.keymap[key] = this.moveLeft
break;
case 'right':
this.keymap[key] = this.moveRight
break;
}
}
this.color = color;
} // Player()
Player.prototype.jump = function() {
if (!this.jumping) {
this.jumping = true;
this.velY = -this.speed * 1.5;
}
}
Player.prototype.moveRight = function() {
if (this.velX < this.speed) {
this.velX++;
}
}
Player.prototype.moveLeft = function() {
if (this.velX > -this.speed) {
this.velX--;
}
}
// Globals
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 700,
height = 600,
keys = [],
friction = .9,
gravity = .9;
canvas.width = width;
canvas.height = height;
// Set up players
var players = [];
players.push(new Player('purple', {
32: 'jump',
37: 'left',
38: 'jump',
39: 'right'
}))
/*players.push(new Player('yellow', {
56: 'jump',
52: 'left',
54: 'right'
}, width-25))*/
players.push(new Player('blue', {
87: 'jump',
65: 'left',
68: 'right'
}, (width-25)/2))
function update() {
ctx.clearRect(0, 0, width, height);
addPlatformsToBottom(); // will add platforms if needed
drawPlatforms();
players.forEach(player => {
// check player-specific keys
for (let i in player.keymap) {
if (keys[i] && typeof player.keymap[i] === 'function')
player.keymap[i].bind(player)();
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width - player.width) {
player.x = width - player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if (player.y >= height - player.height) {
player.y = height - player.height;
player.jumping = false;
player.velY = 0;
}
testPlayerForPlatforms(player);
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}) // player.forEach
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
// console.log(e.keyCode);
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load", function() {
update();
});
function testPlayerForPlatforms(player) {
player.hitPlatform = false; // reset platform hit flag
for (var i = 0; i < platforms.length; i++) {
var p = platforms[i];
if (p.active) {
testPlayer(player, p);
if (player.hitPlatform) {
break; // stop search as player has hit a platform
}
}
}
}
function drawPlatforms() { // draws all platforms and move up
platformInfo.lastPlatformY += platformInfo.speed;
for (var i = 0; i < platforms.length; i++) {
var p = platforms[i];
if (p.active) {
p.yPos += platformInfo.speed;
if (p.yPos + p.height < 0) { // platform above top
p.active = false; // turn it off
} else {
p.draw();
}
}
}
}
function addPlatformsToBottom() {
while (platformInfo.lastPlatformY < ctx.canvas.height) {
generateLevel();
}
}
// some constants and vars to control random generation of platforms
const platformInfo = {
speed: -2.5,
height: 8, // platform height
minLength: 100, // in pixels
maxLength: 300,
vertSpacing: 100, // distance between platforms
minHorSpacing: 50, // should be larger than player
maxHorSpacing: 80,
lastPlatformY: 100, // y position of last platform created
maxHoleCount: 3,
color: "#FFF",
}
// array object holds platforms
const platforms = [];
// a platform template object that will be used to create platforms from
const platform = {
left: 0,
right: 0,
yPos: 0,
height: 0, // thickness
active: false, // true if platform in use
color: "#F84",
draw() { // function to draw the platform
ctx.fillStyle = this.color;
ctx.fillRect(this.left, this.yPos, this.right - this.left, this.height);
},
init(left, right, yPos) { // function to initialize
// alias to save typing.
const pI = platformInfo
this.yPos = yPos;
this.left = left;
this.right = right;
this.height = pI.height;
this.color = pI.color;
this.active = true;
},
}
// function adds platforms to array. If no inactive platforms a
// new one is created
function addPlatform() {
var platform;
for (var i = 0; i < platforms.length; i++) {
if (!platforms[i].active) { // is the platform inactive
platform = platforms[i];
break; // stop searching
}
}
if (!platform) { // if no inactive platform then create a new one
platform = createPlatform();
platforms.push(platform);
}
return platform;
}
// a function to create a platform object
function createPlatform(customProps = {}) { // custom props can be used to modify the
// platform in future. For now it just defaults to empty
return Object.assign({}, platform, customProps);
}
// creates a set of platforms for a single level
function generateLevel() {
var numHoles = randSI(1, platformInfo.maxHoleCount);
var spacing = ctx.canvas.width / (numHoles); // get spacing
var ypos = platformInfo.lastPlatformY;
platformInfo.lastPlatformY += platformInfo.vertSpacing;
var left = 0; // the starting left edge
for (var i = 1; i <= numHoles; i++) { // create numHoles
var platform = addPlatform();
var holeOffset = randSI(-spacing, 0);
platform.init(left, spacing * i + holeOffset, ypos);
left = spacing * i + holeOffset + randSI(platformInfo.minHorSpacing, platformInfo.maxHorSpacing);
}
// add the last platform
platform = addPlatform();
platform.init(left, ctx.canvas.width, ypos);
}
function testPlayer(player, platform) {
var p, pl; // p for player, pl for platform
p = player;
pl = platform;
// is the player above or below platform
if (!(p.x + p.width < pl.left || p.x > pl.right)) { // yes
if (p.velY > 0 && p.y < pl.yPos) { // is player moving down and above platform
if (p.y + p.height > pl.yPos) { //is bottom of player below top of platform
// must have hit platform
p.jumping = false;
p.y = pl.yPos - p.height; // move player so that it is on the platform
p.velY = 0;
p.hitPlatform = true; // flag a platform has been hit
}
} else if (p.y + p.height > pl.yPos + pl.height) { // player must be moving up so check if below platform
if (p.y < pl.yPos + pl.height) { // is top of player above bottom of platform
// must have hit head on platform
p.velY = 0;
p.y = pl.yPos + pl.height;
p.jumping = false;
p.hitPlatform = true; // flag a platform has been hit
}
}
}
}
#score {
color:white;
font-size:35px;
}
0<html>
<head>
<title>Square Stairs™</title>
</head>
<body bgcolor="#000">
<div id="score">SCORE:</div>
<br><br><br> <!-- line breaks to move canvas away from SO title bar that gets in the way when switching to full page mode -->
<canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>
This is my code as it stands currently. I made on the websiteCodePenand this is my original code. I have nothing to do with Unity or any other coding platform so if you have any information on how to solve this it has to be able to run on the CodePen website. Thank you for your assistance.
I've added code to your code, look for ////////////////////
I added the following to your source code:
Added the functions checkPlayerBounds(player) and addToScore(x)
checkPlayerBounds(player) checks if player has been pushed/fell off the screen.
Note: You need to add more functionality here to have the Game Over do what you want.
addToScore(x) increases the score variable and the Score HTML element if scoreShouldUpdate is true.
Added global variables updates, score, and scoreShouldUpdate.
updates keeps track of how many times the update() function has been called.
score keeps track of the games score.
Added code inside your update() function.
The first bit keeps adding to the score, but only after the game has been updated a specified amount of times.
The next bit calls the checkPlayerBounds function on every player.
This all works, the only problem is that the player starts off/right on the edge of the screen, so the score won't update until that is changed in your project.
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
const seeded = (() => {
var seed = 1;
return {
max: 2576436549074795,
reseed(s) {
seed = s
},
random() {
return seed = ((8765432352450986 * seed) + 8507698654323524) % this.max
},
}
})();
const randSeed = (seed) => seeded.reseed(seed);
const randSI = (min, max = min + (min = 0)) => (seeded.random() % (max - min)) + min;
const randS = (min, max = min + (min = 0)) => (seeded.random() / seeded.max) * (max - min) + min;
randSeed(100); // seed the random generators
///////////////////////////
// This function increases the score by 'x' amount.
///////////////////////////
function addToScore(x){
if(scoreShouldUpdate){
score += x;
var scoreElement = document.getElementById("score");
scoreElement.innerHTML = "Score: " + score;
}
}
function checkPlayerBounds(player){
if(player.y >= 0){
scoreShouldUpdate = false;
// Insert game over stuff here.
}
}
function Player(color, keymap, x) {
this.x = (typeof x === 'undefined') ? 1 : x;
this.y = 7;
this.width = 15;
this.height = 15;
this.speed = 10;
this.velX = 0;
this.velY = 0;
this.jumping = false;
this.keymap = {}
for (let key in keymap) {
switch (keymap[key]) {
case 'jump':
this.keymap[key] = this.jump
break;
case 'left':
this.keymap[key] = this.moveLeft
break;
case 'right':
this.keymap[key] = this.moveRight
break;
}
}
this.color = color;
} // Player()
Player.prototype.jump = function() {
if (!this.jumping) {
this.jumping = true;
this.velY = -this.speed * 1.5;
}
}
Player.prototype.moveRight = function() {
if (this.velX < this.speed) {
this.velX++;
}
}
Player.prototype.moveLeft = function() {
if (this.velX > -this.speed) {
this.velX--;
}
}
// Globals
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 700,
height = 600,
keys = [],
friction = .9,
gravity = .9;
//////////////////////////////
//New variables for score increase
//////////////////////////////
var updates = 0;
var score = 0;
var scoreShouldUpdate = true;
canvas.width = width;
canvas.height = height;
// Set up players
var players = [];
players.push(new Player('purple', {
32: 'jump',
37: 'left',
38: 'jump',
39: 'right'
}))
/*players.push(new Player('yellow', {
56: 'jump',
52: 'left',
54: 'right'
}, width-25))*/
players.push(new Player('blue', {
87: 'jump',
65: 'left',
68: 'right'
}, (width-25)/2))
function update() {
/////////////////////////////////////
// You can change the '5' to something else to change the rate of which score is increased.
/////////////////////////////////////
if(updates == 5){
updates = 0;
addToScore(1);
}
updates++;
ctx.clearRect(0, 0, width, height);
addPlatformsToBottom(); // will add platforms if needed
drawPlatforms();
players.forEach(player => {
// check player-specific keys
for (let i in player.keymap) {
if (keys[i] && typeof player.keymap[i] === 'function')
player.keymap[i].bind(player)();
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width - player.width) {
player.x = width - player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if (player.y >= height - player.height) {
player.y = height - player.height;
player.jumping = false;
player.velY = 0;
}
testPlayerForPlatforms(player);
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
//My code
checkPlayerBounds(player);
}) // player.forEach
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
// console.log(e.keyCode);
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load", function() {
update();
});
function testPlayerForPlatforms(player) {
player.hitPlatform = false; // reset platform hit flag
for (var i = 0; i < platforms.length; i++) {
var p = platforms[i];
if (p.active) {
testPlayer(player, p);
if (player.hitPlatform) {
break; // stop search as player has hit a platform
}
}
}
}
function drawPlatforms() { // draws all platforms and move up
platformInfo.lastPlatformY += platformInfo.speed;
for (var i = 0; i < platforms.length; i++) {
var p = platforms[i];
if (p.active) {
p.yPos += platformInfo.speed;
if (p.yPos + p.height < 0) { // platform above top
p.active = false; // turn it off
} else {
p.draw();
}
}
}
}
function addPlatformsToBottom() {
while (platformInfo.lastPlatformY < ctx.canvas.height) {
generateLevel();
}
}
// some constants and vars to control random generation of platforms
const platformInfo = {
speed: -2.5,
height: 8, // platform height
minLength: 100, // in pixels
maxLength: 300,
vertSpacing: 100, // distance between platforms
minHorSpacing: 50, // should be larger than player
maxHorSpacing: 80,
lastPlatformY: 100, // y position of last platform created
maxHoleCount: 3,
color: "#FFF",
}
// array object holds platforms
const platforms = [];
// a platform template object that will be used to create platforms from
const platform = {
left: 0,
right: 0,
yPos: 0,
height: 0, // thickness
active: false, // true if platform in use
color: "#F84",
draw() { // function to draw the platform
ctx.fillStyle = this.color;
ctx.fillRect(this.left, this.yPos, this.right - this.left, this.height);
},
init(left, right, yPos) { // function to initialize
// alias to save typing.
const pI = platformInfo
this.yPos = yPos;
this.left = left;
this.right = right;
this.height = pI.height;
this.color = pI.color;
this.active = true;
},
}
// function adds platforms to array. If no inactive platforms a
// new one is created
function addPlatform() {
var platform;
for (var i = 0; i < platforms.length; i++) {
if (!platforms[i].active) { // is the platform inactive
platform = platforms[i];
break; // stop searching
}
}
if (!platform) { // if no inactive platform then create a new one
platform = createPlatform();
platforms.push(platform);
}
return platform;
}
// a function to create a platform object
function createPlatform(customProps = {}) { // custom props can be used to modify the
// platform in future. For now it just defaults to empty
return Object.assign({}, platform, customProps);
}
// creates a set of platforms for a single level
function generateLevel() {
var numHoles = randSI(1, platformInfo.maxHoleCount);
var spacing = ctx.canvas.width / (numHoles); // get spacing
var ypos = platformInfo.lastPlatformY;
platformInfo.lastPlatformY += platformInfo.vertSpacing;
var left = 0; // the starting left edge
for (var i = 1; i <= numHoles; i++) { // create numHoles
var platform = addPlatform();
var holeOffset = randSI(-spacing, 0);
platform.init(left, spacing * i + holeOffset, ypos);
left = spacing * i + holeOffset + randSI(platformInfo.minHorSpacing, platformInfo.maxHorSpacing);
}
// add the last platform
platform = addPlatform();
platform.init(left, ctx.canvas.width, ypos);
}
function testPlayer(player, platform) {
var p, pl; // p for player, pl for platform
p = player;
pl = platform;
// is the player above or below platform
if (!(p.x + p.width < pl.left || p.x > pl.right)) { // yes
if (p.velY > 0 && p.y < pl.yPos) { // is player moving down and above platform
if (p.y + p.height > pl.yPos) { //is bottom of player below top of platform
// must have hit platform
p.jumping = false;
p.y = pl.yPos - p.height; // move player so that it is on the platform
p.velY = 0;
p.hitPlatform = true; // flag a platform has been hit
}
} else if (p.y + p.height > pl.yPos + pl.height) { // player must be moving up so check if below platform
if (p.y < pl.yPos + pl.height) { // is top of player above bottom of platform
// must have hit head on platform
p.velY = 0;
p.y = pl.yPos + pl.height;
p.jumping = false;
p.hitPlatform = true; // flag a platform has been hit
}
}
}
}
#score {
color:white;
font-size:35px;
}
<html>
<head>
<title>Square Stairs™</title>
</head>
<body bgcolor="#000">
<div id="score">SCORE:</div>
<br><br><br> <!-- line breaks to move canvas away from SO title bar that gets in the way when switching to full page mode -->
<canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>

Why isnt the bird colliding with the ledges?

I am making a flappy bird game using phaser.js.
My problem is that it doesn't collide with the ledges. And how do you change the camera (you know in flappy bird they like move the camera)?
Any other tips on making my game would be greatly appreciated!
JSFiddle
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-demo', {
preload: preload,
create: create,
update: update,
render: render
});
var player;
var starfield;
var cursors;
var fireButton;
var gameOver;
var upLedge;
var vaRandomUpLedgeSize;
var bottomLedge;
function preload() {
game.load.image('starfield', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJAAAAEACAYAAABcV/9PAAAEWklEQVR42u3ZsW7UShSA4XltxAMgxGPwHHSwRSQaKpR0FCDRQY+AgAzeiccej8fesf0Vn8Llru2zJ//aubnh+bv3P6FUsAQEhIAQEAICASEgBISAQEAIiJYDevv7D1BIQAgIASEgBAQCQkDsKCC/DMNvohEQAkJAICAEhIAQEAgIASEgBAQCQkAICAGBgBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIBAQAkJACAgBgYAQEAJCQCAgBISAEBAICAEhIAQEAkJACAgBISBLQEAICAEhIBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIAQEAkJACAgBgYAQEAJCQCAgBISAEBAICAEhIASEgEBACAgBISAQEAJCQAgIBISAEBACAgEhIASEgEBACAgBISAEBAJCQAgIAYGAEBACQkAgIASEgBAQCAgBISAEhIBAQAgIATHD1x8PgwREUTh7Cykc9ZPR6t0iN5y97D0c9ZNxi7vF1F5K42l552FPn4ytZ6j5zV4aT+p93vr7EvbwyVhjjqlz1PiGd+erda6S+db8gD7+u1D7jbVwB1jzMbJXtT+g3d+FrYbc8vGx1iPkaBHVOGeTAd3qdn+miGqdL2xxq6zxWtq0akBrHsNBA0JAICAEhICuvfly+ef1x/snzjbHEXayeUAP3+/+eByq+3P3z2eb4wg7WRTQp28fnki9dqjqx+G6wZcsq5U5zriTUGu4nCH7VcdKltXKHGfeSZj7vE0NN1Rx/7xx1fHXuc/+VuY4+07CnNvlWN1DFXc/kOUOmTtLK3PYSXQHmio+Z8j+D2NDQ47dJnNnaWUOO7n/fwcaOih+fs65NZbcJnNmaWUOO/lrcUCpavu/U9hiWVvPYSdRQEMH5SwrdXx/yKk3FA85Nksrc9jJZbuAuq+3XlbNOezkst4jLPW83fp2veYcdrLiIywevv93OUPW+rStOYedzHyEpf7zcGzIscGXPDpaneOMO8l+hOX+gqr/P+OmBi99dLQ6xxl3ErqDh752wzy7e3El/l1DfFx/+PjY1PXi1835tKWOzTl36WNjbCdTj4742NT1au+k/70p3Ul87GhA3Ytefn51pR9DKqCpY+Nhxl6XWtbUsbkzzHls5OwkFdDedzJ0bBi61aUukvvGc46fe41uYTWvEX9D4jvC2XfSjyZ1XIhvYzlvYG7VU+fIOWfNawxdZ+haJTtZY94WdpI6dyj5BJR+YsbeyJJl5F5jzfd4lJ3MPXfIufBQlaWfyrl3sKXXyLlOSRhH3EnJucNat+Ean6yly6o9v51kBlTjFrnlebe4jp1kBlTrFrn0vEuXVfP1dpJ+TSgdCCZ/BgIBISAEhIBAQAgIASEgEBACQkAICAGBgBAQAkJAICAEhIAQEAgIASEgBAQCQkAICAEhIBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIBAQAkJACAgBgYAQEAJCQCAgBISAEBAICAHRlF+C+UHwNeMuEwAAAC10RVh0U29mdHdhcmUAYnkuYmxvb2RkeS5jcnlwdG8uaW1hZ2UuUE5HMjRFbmNvZGVyqAZ/7gAAAABJRU5ErkJggg==');
game.load.image('player', 'https://i.imgur.com/JArA3tQ.png');
game.load.image('upLedge', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAACGCAYAAADZ0np4AAAAiklEQVR42u3UsQ2DQAwF0FslPT0jpE+BmIQBaLMDw2QUSpY45IIrTggFQVK94tvds2TJTnN+52npS4ZPU/q36cZH6ZFX+8wJDAaDwWAwGAwGg8FgMBgMBoPBYDAYDAaDwWAwGAwGg8FgMBgM3oej/CJpm3J30pUVHK0DDP4nHCd9JjG8fgP1Swh4Bcd7BZH+S2fyAAAALXRFWHRTb2Z0d2FyZQBieS5ibG9vZGR5LmNyeXB0by5pbWFnZS5QTkcyNEVuY29kZXKoBn/uAAAAAElFTkSuQmCC');
game.load.image('bottomLedge', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAB6CAYAAABQtRgZAAAAgklEQVR42u3TsQmAMBQFwKxib+8I9hbiJA5g6w4O4yiWLhFRUERslAgWF3h5pDmSwA9VUcbUCVPs45MMc3P0Xdoxj+F82PtN6i47GgpNja5b6oTPxvQ6Zk+/4fz07aZQKBQKhUKhUCgUCoVCoVAoFAqFQqFQKBQKhUKhUCj0n+gXawGd+WGo+T+h1gAAAC10RVh0U29mdHdhcmUAYnkuYmxvb2RkeS5jcnlwdG8uaW1hZ2UuUE5HMjRFbmNvZGVyqAZ/7gAAAABJRU5ErkJggg==');
}
function create() {
// The scrolling starfield background
game.physics.startSystem(Phaser.Physics.ARCADE);
starfield = game.add.tileSprite(0, 0, 800, 600, 'starfield');
starfield.scale.setTo(1, 2.5);
starfield.enableBody = true;
// The hero!
player = game.add.sprite(50, 400, 'player');
player.anchor.setTo(0.5, 0.5);
player.scale.setTo(1.25, 1.5);
game.physics.arcade.enable(player);
game.physics.enable(player, Phaser.Physics.ARCADE);
player.body.gravity.y = 450;
player.body.collideWorldBounds = true;
upLedge = game.add.sprite(400, 0, 'upLedge');
bottomLedge = game.add.sprite(400, 365, 'bottomLedge');
randomLedgeSize();
upLedge.scale.setTo(1, vaRandomUpLedgeSize);
randomLedgeSize();
bottomLedge.scale.setTo(1, vaRandomUpLedgeSize);
fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
// And some controls to play the game with
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
// Scroll the background
starfield.tilePosition.x -= 2;
player.x++;
//SPACEBAR
if (player.y >= 591.75) {
player.y = 591.75;
player.x--;
}
if (fireButton.isDown) {
player.body.velocity.y = -250;
}
game.physics.arcade.collide(player, upLedge);
game.physics.arcade.collide(player, bottomLedge);
}
function render() {
}
function randomLedgeSize() {
vaRandomUpLedgeSize = Math.floor(Math.random() * (3 - 1)) + 1;
if (vaRandomUpLedgeSize <= 1.5) {
vaRandomUpLedgeSize = 1;
} else {
vaRandomUpLedgeSize = 2;
}
}
function randomLedgeSizeBot() {
vaRandomUpLedgeSize = Math.floor(Math.random() * (3 - 1)) + 1;
if (vaRandomUpLedgeSize <= 1.5) {
bottomLedge.y = 500;
} else {
vaRandomUpLedgeSize = 2;
}
}
See here:
The collisions only fire if the sprite.body has velocity.
So what I did was change the update() function: I removed the call to player.x++; and in the create() function I added an X velocity to the player.
JSfiddle
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-demo', {
preload: preload,
create: create,
update: update,
render: render
});
var player;
var starfield;
var cursors;
var fireButton;
var gameOver;
var ledges;
function preload() {
game.load.image('starfield', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJAAAAEACAYAAABcV/9PAAAEWklEQVR42u3ZsW7UShSA4XltxAMgxGPwHHSwRSQaKpR0FCDRQY+AgAzeiccej8fesf0Vn8Llru2zJ//aubnh+bv3P6FUsAQEhIAQEAICASEgBISAQEAIiJYDevv7D1BIQAgIASEgBAQCQkDsKCC/DMNvohEQAkJAICAEhIAQEAgIASEgBAQCQkAICAGBgBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIBAQAkJACAgBgYAQEAJCQCAgBISAEBAICAEhIAQEAkJACAgBISBLQEAICAEhIBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIAQEAkJACAgBgYAQEAJCQCAgBISAEBAICAEhIASEgEBACAgBISAQEAJCQAgIBISAEBACAgEhIASEgEBACAgBISAEBAJCQAgIAYGAEBACQkAgIASEgBAQCAgBISAEhIBAQAgIATHD1x8PgwREUTh7Cykc9ZPR6t0iN5y97D0c9ZNxi7vF1F5K42l552FPn4ytZ6j5zV4aT+p93vr7EvbwyVhjjqlz1PiGd+erda6S+db8gD7+u1D7jbVwB1jzMbJXtT+g3d+FrYbc8vGx1iPkaBHVOGeTAd3qdn+miGqdL2xxq6zxWtq0akBrHsNBA0JAICAEhICuvfly+ef1x/snzjbHEXayeUAP3+/+eByq+3P3z2eb4wg7WRTQp28fnki9dqjqx+G6wZcsq5U5zriTUGu4nCH7VcdKltXKHGfeSZj7vE0NN1Rx/7xx1fHXuc/+VuY4+07CnNvlWN1DFXc/kOUOmTtLK3PYSXQHmio+Z8j+D2NDQ47dJnNnaWUOO7n/fwcaOih+fs65NZbcJnNmaWUOO/lrcUCpavu/U9hiWVvPYSdRQEMH5SwrdXx/yKk3FA85Nksrc9jJZbuAuq+3XlbNOezkst4jLPW83fp2veYcdrLiIywevv93OUPW+rStOYedzHyEpf7zcGzIscGXPDpaneOMO8l+hOX+gqr/P+OmBi99dLQ6xxl3ErqDh752wzy7e3El/l1DfFx/+PjY1PXi1835tKWOzTl36WNjbCdTj4742NT1au+k/70p3Ul87GhA3Ytefn51pR9DKqCpY+Nhxl6XWtbUsbkzzHls5OwkFdDedzJ0bBi61aUukvvGc46fe41uYTWvEX9D4jvC2XfSjyZ1XIhvYzlvYG7VU+fIOWfNawxdZ+haJTtZY94WdpI6dyj5BJR+YsbeyJJl5F5jzfd4lJ3MPXfIufBQlaWfyrl3sKXXyLlOSRhH3EnJucNat+Ean6yly6o9v51kBlTjFrnlebe4jp1kBlTrFrn0vEuXVfP1dpJ+TSgdCCZ/BgIBISAEhIBAQAgIASEgEBACQkAICAGBgBAQAkJAICAEhIAQEAgIASEgBAQCQkAICAEhIBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIBAQAkJACAgBgYAQEAJCQCAgBISAEBAICAHRlF+C+UHwNeMuEwAAAC10RVh0U29mdHdhcmUAYnkuYmxvb2RkeS5jcnlwdG8uaW1hZ2UuUE5HMjRFbmNvZGVyqAZ/7gAAAABJRU5ErkJggg==');
game.load.image('player', 'https://i.imgur.com/JArA3tQ.png');
game.load.image('upLedge', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAACGCAYAAADZ0np4AAAAiklEQVR42u3UsQ2DQAwF0FslPT0jpE+BmIQBaLMDw2QUSpY45IIrTggFQVK94tvds2TJTnN+52npS4ZPU/q36cZH6ZFX+8wJDAaDwWAwGAwGg8FgMBgMBoPBYDAYDAaDwWAwGAwGg8FgMBgM3oej/CJpm3J30pUVHK0DDP4nHCd9JjG8fgP1Swh4Bcd7BZH+S2fyAAAALXRFWHRTb2Z0d2FyZQBieS5ibG9vZGR5LmNyeXB0by5pbWFnZS5QTkcyNEVuY29kZXKoBn/uAAAAAElFTkSuQmCC');
game.load.image('bottomLedge', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAB6CAYAAABQtRgZAAAAgklEQVR42u3TsQmAMBQFwKxib+8I9hbiJA5g6w4O4yiWLhFRUERslAgWF3h5pDmSwA9VUcbUCVPs45MMc3P0Xdoxj+F82PtN6i47GgpNja5b6oTPxvQ6Zk+/4fz07aZQKBQKhUKhUCgUCoVCoVAoFAqFQqFQKBQKhUKhUCj0n+gXawGd+WGo+T+h1gAAAC10RVh0U29mdHdhcmUAYnkuYmxvb2RkeS5jcnlwdG8uaW1hZ2UuUE5HMjRFbmNvZGVyqAZ/7gAAAABJRU5ErkJggg==');
}
function create() {
// The scrolling starfield background
game.physics.startSystem(Phaser.Physics.ARCADE);
starfield = game.add.tileSprite(0, 0, 800, 600, 'starfield');
starfield.scale.setTo(1, 2.5);
// The hero!
player = game.add.sprite(50, 400, 'player');
player.anchor.setTo(0.5, 0.5);
player.scale.setTo(1.25, 1.5);
game.physics.arcade.enable(player);
game.physics.enable(player, Phaser.Physics.ARCADE);
player.enableBody = true;
player.body.gravity.y = 450;
player.body.collideWorldBounds = true;
player.body.velocity.x = 100;
// The ledges
ledges = game.add.group();
ledges.enableBody = true;
var upLedge = ledges.create(200, 0, 'upLedge');
upLedge.body.immovable = true;
var bottomLedge = ledges.create(200, 465, 'bottomLedge');
bottomLedge.body.immovable = true;
// Controls to play the game with
fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
// Scroll the background
starfield.tilePosition.x -= 2;
// If spacebar is pressed, increase Y velocity
if (fireButton.isDown) {
player.body.velocity.y = -250;
}
// Check for collisions
game.physics.arcade.collide(player, ledges);
}
function render() {
}

Categories