Phaser game/school project, need guidance - javascript

I am studying javascript at a very basic level, we have a school assaignment where the teacher handed out a simple game for each student. The task here is to change the game a little. I am very bad at javascript and I would like some help by someone skilled. My question is : How do I make the gates appear at random coordinates? right now it looks like this :
window.onload = function() {
class MazeToGoal extends Phaser.Scene {
constructor (config)
{
super(config);
Phaser.Scene.call(this, { key: "MazeToGoal", active: true });
this.gameOn=true;
this.score=0;
this.scoreMsg="Score: ";
this.scoreText;
this.my_buttons = [];
this.step=4;
this.counter;
this.gates=[];
}
preload() {
this.load.spritesheet('mushrooms', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAIAAABMXPacAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAL8SURBVHhe7dHRcqMwEETR/f+fzlZtXW/jAmKITY+T3PPYIwmh/vOhURYwzAKGWcAwCxhmAcMsYJgFDLOAYRYwzAKGfY8C/pzEtu/gve7K+12Gz7yT4TvxMEO4xKiBS/D3b4bL1fU+zI++Pa7bcvn3+K3ncNYZ7HwCB13sws/wHyex+Rp84wx2XuaSD3D3A9gwhEscw55Xe/G5XPYRVr8NrnUAG17nZSdywU+x9I1x0UdY/QovOItL7WPdt8LV97HuaU8dxF32se7b4jf2se4JXz+CK+xg0Y/AL+1g0Vd9cT8f38KKH4ff28Gi807v5INbWPGj8atbWHHSuW18aoXxr8FvrzA+48QePrLC+Jfh51cYH3Z0A8ffY/aL8RD3mB1zaDUH32P26/Ec95gd8MUCGOgfHuUes0cer+O8BQZa4GkWGDzyYB2HLTDQCg+0wOBTny3imAUG2sEzLTDYZwGvxDMtMNi3u4IDFhjoUzzWAoMdRwsg1QE82Q3pju0xWxcY6ACebIHBlkMFkOowHu6GdIsFXIKHuyHdYgGX4OFuSLdszNikl+JxVyyghMddsYASHnfFAkp43BULKOFxV3YH1+FGN6QTuMENaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRplwUEaZcFBGmXBQRp13wB74P7dVlAcL8uCwju12UBwf26LCC4X9fMV/WfBQyzgGEWMMwChlnAMAsYZgHDLGCYBQyzgGEWMMwChlnAMAsYZgHDLGCYBQyzgGEWMOrj4y8tsH+sT76qdwAAAABJRU5ErkJggg==', { frameWidth: 128, frameHeight: 128});
}
create ()
{
this.pen = this.make.graphics({x: 0, y: 0, add: false});
this.pen.fillStyle(0x00FF00, 1.0);
this.pen.fillRect(0, 0, 30, 30);
this.pen.generateTexture('goal', 30, 30);
this.player = this.add.image(100, 270, 'goal');
this.scoreText = this.add.text(10, 10, this.scoreMsg+this.score, { fontSize: '32px', fill: '#FFF' });
this.counter=0;
this.gates[0] = this.createGate(100);
this.cursors = this.input.keyboard.createCursorKeys();
}
update()
{
if(this.gameOn) {
this.counter++;
if(this.counter % 200 === 0) {
this.gates.push(this.createGate(100));
}
if (this.cursors.up.isDown)
{
this.player.y-=this.step;
}
else if (this.cursors.down.isDown)
{
this.player.y+=this.step;
}
if(this.player.x-5 < this.gates[0].left.x && this.gates[0].left.x < this.player.x+5) {
if(this.gates[0].left.y < this.player.y && this.player.y < this.gates[0].right.y) {
console.log("Hit");
this.gates.shift();
}
else {
this.gameOn=false;
this.add.text(25, 200,"Game Over", { fontSize: '128px', fill: '#F00' });
console.log("Boom");
}
}
}
}
createGate(StartY) {
let gate={};
gate.left = this.add.image(700,StartY, 'mushrooms', 1).setScale(0.25);
gate.right = this.add.image(700, StartY+100, 'mushrooms', 1).setScale(0.25);
gate.tween = this.tweens.add({
targets: [gate.left, gate.right] ,
x: -50,
//ease: 'Power1',
duration: 5000
});
return gate;
}
}
const config = {
type: Phaser.WEBGL,
width: 800,
height: 600,
backgroundColor: "#FFFFFF",
parent: "phaser-example",
scene: [MazeToGoal]
};
const game = new Phaser.Game(config);
}
<head>
<meta charset="utf-8" />
<title>MushroomSlalom</title>
<script src="https://cdn.jsdelivr.net/npm/phaser#3.1.1/dist/phaser.min.js"></script>
</head>
<body>
<div id="phaser-example"></div>
</body>
Thanks in advance!

In Phaser 3, you can use Phaser.Math.Between() to generate a random number.
So to make gates appear at random locations, determine what area you would want the gates to spawn in, and generate random coordinates within that space.
If you wanted them to spawn anywhere on screen, you could do something like the following.
// Update as needed. Here we have it based upon the width and height of the main camera.
let randomX = Phaser.Math.Between(0, this.cameras.main.width);
let randomY = Phaser.Math.Between(0, this.cameras.main.height);
let gate = this.add.image(randomX, randomY, 'mushrooms', 1);
This ignores that part of the image might be off-screen; you'd want to add an appropriate buffer to account for the anchor point.

Related

Phaser 3 Arcade Gravity Isn't working properly no matter what value i set it to

I'm working on a new project in phaser and for some reason the gravity in the game is all messed up, when i attempt to jump i jump like a centimeter. if i change the values nothing changes its always glitched. how can i make it so that i jump and fall normally?
I've had some previous projects and the gravity works just fine, for this project i am using the latest stable release of phaser 3. I honestly cant see what the error is and i've been at it for a while.
there was a lot of code that wasn't relevent to the error so i removed it to make it easier for someone to review this.
game.js
const socket = io();
var config = {
type: Phaser.AUTO,
width: 1000,
height: 550,
parent: 'master',
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: true
}
},
scene: {
preload: resources,
create: mechanics,
update: controls
}
};
const game = new Phaser.Game(config);
function resources() {
this.load.image("arena", "../resources/images/arena1.png");
this.load.image("floor", "../resources/images/floor.png");
this.load.atlas("warrior", "../resources/images/characters/warrior.png","../resources/images/characters/warrior.json");
}
var warrior;
function mechanics() {
grasslands = this.add.image(500, 225, "arena").setScale(0.7);
warrior = this.physics.add.sprite(100, 490, "warrior").setScale(2).setSize(15, 15);
floor = this.physics.add.staticGroup();
floor.create(500, 545, "floor").setVisible(false);
this.physics.add.collider(warrior, floor);
warrior.body.collideWorldBounds = true;
warrior.body.onWorldBounds = true;
}
function controls() {
key = this.input.keyboard.addKeys("W,A,S,D");
if(key.A.isDown) {
warrior.setVelocityX(-100);
warrior.flipX = true;
}else if (key.D.isDown) {
warrior.setVelocityX(100);
warrior.flipX = false;
}else if (key.W.isDown && warrior.body.touching.down) {
warrior.setVelocityY(-330);
}else{
warrior.setVelocity(0);
}
}
The problem occurs because of this line warrior.setVelocity(0);. This line, stops the gravity of working, as intended (and hinders jumping), since on scene updates, the velocity is set to 0. Remove that line and add warrior.setVelocityX(0) at the start of the controls function and everything should work fine (if you want/have to keep the if-else block). Or check out my working demo at the end of this answer.
function controls() {
key = this.input.keyboard.addKeys("W,A,S,D");
warrior.setVelocityX(0);
if(key.A.isDown) {
warrior.setVelocityX(-100);
warrior.flipX = true;
}else if (key.D.isDown) {
warrior.setVelocityX(100);
warrior.flipX = false;
}else if (key.W.isDown && warrior.body.touching.down) {
warrior.setVelocityY(-330);
}
}
I would only stop the left/right movement, when the player stops pressing the keys ( with setVelocityX(0)), and let gravity take care of stopping the jump/upwards movement.
Here a basic demo:
var config = {
type: Phaser.AUTO,
width: 400,
height: 160,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 200 },
}
},
scene: {
create,
update
}
};
var cursors;
var player;
var playerStateText;
const SPEED = 250;
var isJumping = true;
function create () {
cursors = this.input.keyboard.createCursorKeys();
this.add.text(10, 10, 'Use arrow Keys to move!')
let ground = this.add.rectangle(-40, 120, 480, 50, 0xBAF0FF).setOrigin(0);
player = this.add.rectangle(20, 20, 30, 30, 0xcccccc).setOrigin(0);
ground = this.physics.add.existing(ground);
ground.body.setImmovable(true);
ground.body.allowGravity = false;
player = this.physics.add.existing(player);
this.physics.add.collider(player, ground, _ => isJumping = false);
}
function update (){
if (cursors.left.isDown){
player.body.setVelocityX(-SPEED);
} else if (cursors.right.isDown) {
player.body.setVelocityX(SPEED);
}
else {
player.body.setVelocityX(0);
}
if (!isJumping && cursors.up.isDown){
player.body.setVelocityY(-SPEED * .75);
isJumping = true;
}
}
new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

How to get target who are touching on a specific sprite

I am trying to make a mini-game by phaser.js. In my idea. A sprite object can collided to a static sprite and continually perform desired effect if they are stick together. However, when I handle them with this.physics.add.collider, the callback function just run once.
Search for API document. I find the touching event can be judged by object.body.touching. But seen it can only return the facing. So I wonder how to get the object who are touching on the specific direction of a sprite? Or the function is need to handle by handy?
Thanks for your help.
If you need more "detailed"/"better" physics functions in phaser, you could use the matterjs physics engine.
(It is as easy as the arcade engine, atleast to setup)
With matterjs there are more options, like the "collisions events", using matter you could use the event collisionactive.
(link to the documentation)
collisionactive executes as long as the two colliding objects touch.
Like this you know the exact object(s) touching. (And if you need the direction you could find it with the x and y postions of the objects, or the velocity of the impact)
Here a demo from the offical website, showing collisionstart Event https://phaser.io/examples/v3/view/physics/matterjs/collision-event
Here a small with matter demo:
// Minor formating for stackoverflow
document.body.style = "display: flex;flex-direction: column;";
var config = {
type: Phaser.AUTO,
width: 536,
height: 153,
backgroundColor: '#1b1464',
physics: {
default: 'matter',
matter: {
debug:true,
gravity:{y:0, x:0}
}
},
scene: {
create: create
}
};
var game = new Phaser.Game(config);
var counter = 0;
var gOverlay;
function create ()
{
var blockA = this.matter.add.image(50, 80, 'block1');
var blockB = this.matter.add.image(300, 80, 'block1').setStatic(true);
var text = this.add.text(10,10, 'Not touching')
blockA.setVelocityX(3);
gOverlay = this.add.graphics();
this.matter.world.on('collisionstart', function (event, bodyA, bodyB) {
text.setText(text.text + '\nHIT')
drawDirectionArrow(bodyA, bodyB)
});
this.matter.world.on('collisionactive', function (event, bodyA, bodyB) {
text.setText(`Touching: ${counter++}`)
if(counter > 60 ) {
counter = 0;
blockA.setVelocityX(-2);
}
});
this.matter.world.on('collisionend', (function (event, bodyA, bodyB) {
text.setText(text.text + '\nNot touching');
gOverlay.clear();
this.time.delayedCall(2000, _ => blockA.setVelocityX(5));
}).bind(this));
}
function drawDirectionArrow(a, b){
gOverlay.clear();
gOverlay.fillStyle( 0xFF00FF);
gOverlay.fillTriangle(a.position.x, a.position.y, b.position.x, b.position.y - 10, b.position.x, b.position.y + 10);
}
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js">
</script>
Update:
If you need/want to use arcade physics, here is a similar demo, with a small workaround using a second physics-object to check for overlap.
Arcade - Physics workaround - Demo:
// Minor formating for stackoverflow
document.body.style = "display: flex;flex-direction: column;";
var config = {
type: Phaser.AUTO,
width: 536,
height: 153,
backgroundColor: '#1b1464',
physics: {
default: 'arcade',
arcade: {
debug:true,
}
},
scene: {
create: create
}
};
var game = new Phaser.Game(config);
var counter = 0;
var gOverlay;
function create () {
var blockA = this.physics.add.image(50, 80, 'block1').setOrigin(.5);
var blockB = this.physics.add.image(300, 80, 'block1').setOrigin(.5);
// Helper
var blockBx = this.add.rectangle(300, 80, 34, 34);
this.physics.add.existing(blockBx);
blockB.setImmovable();
var text = this.add.text(10,10, 'Not touching')
blockA.setVelocityX(50);
gOverlay = this.add.graphics();
this.physics.add.collider(blockA, blockB, function ( bodyA, bodyB) {
drawDirectionArrow(bodyA, bodyB);
})
this.physics.add.overlap(blockA, blockBx, function ( bodyA, bodyB) {
text.setText(`Touching: ${counter++}`);
if(counter > 60 ) {
counter = 0;
gOverlay.clear();
blockA.setVelocityX(-50);
text.setText('Not touching');
this.time.delayedCall(2000, _ => blockA.setVelocityX(50));
}
}, null, this);
}
function drawDirectionArrow(a, b){
gOverlay.clear();
gOverlay.fillStyle( 0xFF00FF);
gOverlay.fillTriangle(a.x, a.y, b.x, b.y - 10, b.x, b.y + 10);
}
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js">
</script>

Creating A Bullet Sprite At Players Sprite Location In Phaser But The Sprite Wont Be Created / Added To The Game

This is a game where the monkey moves around the platforms collecting coins. I want to have the monkey shoot a banana when the down arrow and left arrow are pressed.
How would I create the bullet?
I have the keypress for the shooting and it calls shootR or shootL depending on which arrow is pressed. What I need is to create the projectile and have it move to the right or left(not affected by gravity). Can I get some help creating this projectile as var proj = projs.create(x, y, 'proj'); is not working. I am good at coding with js and phaser is new to me so help would be greatly appreciated.
var config = {
type: Phaser.AUTO,
width: 1900,
height: 1000,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var main = document.getElementById("startBtn")
var heading = document.getElementById("header")
var gameOver
var platforms;
var score = 0;
var scoreText;
var leafAm = 0
var leafText
var gunAm = 0
var ammoAm = 0
var ammoText
var monkeyType = "monkey"
var delay = 0
function start() {
game = new Phaser.Game(config);
main.innerHTML = ''
heading.innerHTML += '<h1 class="header2" onclick="shop()"><u>Click To Access Shop</u></h1>'
}
function preload() {
this.load.image('Background', 'assets/Background.jpg');
this.load.image('ground', 'assets/platform.png');
this.load.image('coin', 'assets/coin.png');
this.load.image('redCoin', 'assets/redCoin.png');
this.load.spritesheet('monkey', 'assets/monkey.png', { frameWidth: 600, frameHeight: 720 });
this.load.spritesheet('proj', 'assets/bullet.png', { frameWidth: 200, frameHeight: 200 });
}
function create() {
this.add.image(500, 275, 'Background').setScale(3);
platforms = this.physics.add.staticGroup();
platforms.create(200, 650, 'ground').setScale(0.15).refreshBody();
platforms.create(600, 400, 'ground').setScale(0.15).refreshBody();
platforms.create(1600, 650, 'ground').setScale(0.15).refreshBody();
platforms.create(750, 100, 'ground').setScale(0.15).refreshBody();
platforms.create(850, 750, 'ground').setScale(0.15).refreshBody();
platforms.create(100, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(400, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(700, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1000, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1300, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1600, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1900, 950, 'ground').setScale(0.15).refreshBody();
platforms.create(1800, 800, 'ground').setScale(0.15).refreshBody();
platforms.create(250, 250, 'ground').setScale(0.15).refreshBody();
platforms.create(1000, 500, 'ground').setScale(0.15).refreshBody();
platforms.create(1150, 220, 'ground').setScale(0.15).refreshBody();
player = this.physics.add.sprite(100, 450, 'monkey').setScale(0.075);
this.physics.add.collider(player, platforms);
player.setBounce(0.2);
player.setCollideWorldBounds(true);
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('monkey', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [{ key: 'monkey', frame: 4 }],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('monkey', { start: 5, end: 8 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'shoot',
frames: this.anims.generateFrameNumbers('proj', { start: 0, end: 3 }),
framerate: 15,
repeat: -1
})
coins = this.physics.add.group({
key: 'coin',
repeat: 10,
setXY: { x: 12, y: 0, stepX: 150 }
});
coins.children.iterate(function (child) {
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
child.setScale(0.05)
});
this.physics.add.collider(coins, platforms);
this.physics.add.overlap(player, coins, collectCoin, null, this);
redCoins = this.physics.add.group();
this.physics.add.collider(redCoins, platforms);
this.physics.add.collider(player, redCoins, hitredCoin, null, this);
projs = this.physics.add.group()
this.physics.add.collider(projs, platforms)
this.physics.add.collider(projs, redCoins, shootredCoin, null, this)
scoreText = this.add.text(16, 16, 'Score: 0₴', { fontSize: '40px', fill: 'rgb(85, 1, 1)' });
ammoText = this.add.text(16, 66, 'Ammo: 0🍌', { fontSize: '40px', fill: 'rgb(85, 1, 1)' });
leafText = this.add.text(16, 116, 'Shields: 0🍃', { fontSize: '40px', fill: 'rgb(85, 1, 1)' });
}
function update() {
cursors = this.input.keyboard.createCursorKeys();
if (cursors.down.isDown && cursors.left.isDown && delay == 0) {
shootL()
} else if (cursors.down.isDown && cursors.right.isDown && delay == 0) {
shootR()
}
if (cursors.left.isDown) {
player.setVelocityX(-240);
player.anims.play('left', true);
}
else if (cursors.right.isDown) {
player.setVelocityX(240);
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 collectCoin(player, coin) {
coin.disableBody(true, true);
score += 1;
scoreText.setText('Score: ' + score + '₴');
if (coins.countActive(true) === 0) {
coins.children.iterate(function (child) {
child.enableBody(true, child.x, 0, true, true);
});
var x = Phaser.Math.Between(0, 800);
var redCoin = redCoins.create(x, 16, 'redCoin').setScale(0.05);
redCoin.setBounce(1);
redCoin.setCollideWorldBounds(true);
redCoin.setVelocity(Phaser.Math.Between(-300, 300), 20);
}
}
function shootR(player, redCoin, proj) {
var x = player.x
var y = player.y
var proj = projs.create(x, y, 'proj');
// proj.setVelocityX(-240);
// player.anims.play('shoot', true);
ammoAm -= 1
ammoText.setText('Ammo: ' + ammoAm + '🍌');
delay = 1
this.time.delayedCall(3000, delayer, null, this);
}
function shootL(player, redCoin, proj) {
var x = player.x
var y = player.y
var proj = projs.create(x, y, 'proj');
ammoAm -= 1
ammoText.setText('Ammo: ' + ammoAm + '🍌');
delay = 1
this.time.delayedCall(3000, delayer, null, this);
}
function hitredCoin(player, redCoin) {
if (leafAm > 0) {
leafAm -= 1
leafText.setText('Shields: ' + leafAm + '🍃');
redCoin.disableBody(true, true);
var x = Phaser.Math.Between(0, 800);
var redCoin = redCoins.create(x, 16, 'redCoin').setScale(0.05);
redCoin.setBounce(1);
redCoin.setCollideWorldBounds(true);
redCoin.setVelocity(Phaser.Math.Between(-300, 300), 20);
} else {
this.physics.pause();
player.setTint(0xff0000);
player.anims.play('turn');
gameOver = true;
this.time.delayedCall(3000, restart, null, this);
}
}
function shootredCoin(projs, redCoin) {
redCoin.disableBody(true, true);
projs.disableBody(true, true);
}
function restart() {
score = 0
var leafAm = 0
var gunAm = 0
var ammoAm = 0
this.scene.stop();
this.scene.start();
}
function shop() {
main.innerHTML = `<button class="shopBackground"></button>`
main.innerHTML += `<button class="shop1">Shop</button>`
main.innerHTML += `<button class="shop2">Warning: Shop Fast, you can still die</button>`
main.innerHTML += `<button class="shop3" onclick = "buy1()">Banana Gun...₴100.00<br>(Ability to shoot bananas)<br>click here to buy</button>`
main.innerHTML += `<button class="shop4" onclick = "buy2()">Leaf Shield...₴30.00<br>(Protection from 1 hit)<br>click here to buy</button>`
main.innerHTML += `<button class="shop5" onclick = "buy3()">Bananas...₴10.00<br>(Extra ammo, gun comes with 1)<br>click here to buy</button>`
main.innerHTML += `<button class="shop6">₴ is score</button>`
main.innerHTML += `<button class="shop7" onclick="main.innerHTML = ''">Back To Game</button>`
main.innerHTML += `<img src="/assets/banana1.png" class="banana1">`
main.innerHTML += `<img src="/assets/banana2.png" class="banana2">`
main.innerHTML += `<img src="/assets/leaf.png" class="leaf">`
}
function buy1() {
if (score > 99 && gunAm < 1) {
gunAm += 1
ammoAm += 1
score -= 100
scoreText.setText('Score: ' + score + '₴');
alert("You have bought a gun \nClick the down arrow and either left or right to shoot\nShooting costs ammo but bullets detroy the red orbs\nEnjoy and good luck")
} else if (gunAm > 0) {
alert("You already have one")
} else {
alert("Not enough score")
}
}
function buy2() {
if (score > 29) {
leafAm += 1
score -= 30
scoreText.setText('Score: ' + score + '₴');
leafText.setText('Shields: ' + leafAm + '🍃');
} else {
alert("Not enough score")
}
}
function buy3() {
if (score > 9) {
ammoAm += 1
score -= 10
scoreText.setText('Score: ' + score + '₴');
ammoText.setText('Ammo: ' + ammoAm + '🍌');
;
} else {
alert("Not enough score")
}
}
function delayer() {
delay = 0
}
Any Help Or Ideas On This Would Be Appreciated.
There is also some HTML and CSS but those parts aren't affecting it or at least they shouldn't be
There are somethings to unpack here,
Btw.: usually on stackoverflow you should only post the essential code: https://stackoverflow.com/help/minimal-reproducible-example this makes helping easy
But back to your question:
First of all, the functions shootR and shootL don't work because, they are defined with parameters, but they are not passed. So the player parameter is overloading the global player variable (btw. the global player variable is never declared with var, let or const)
function definitions:
function shootR(player, redCoin, proj)
...
functions being called:
...
if (cursors.down.isDown && cursors.left.isDown && delay == 0) {
shootL()
} else if (cursors.down.isDown && cursors.right.isDown && delay == 0) {
shootR()
}
...
Quick fix: pass the player parameter, example: shootR(player)
Second the this in the shootR and shootL functions, are not pointing to the right object.
Quick fix: Pass the scene to the function, example: shootR(this, player) and alter the functions to:
function shootL(scene, player, redCoin, proj) {
var x = player.x
var y = player.y
var proj = projs.create(x, y, 'proj');
ammoAm -= 1
ammoText.setText('Ammo: ' + ammoAm + '🍌');
delay = 1
scene.time.delayedCall(3000, delayer, null, scene);
}
third to "remove the gravity", just use
Quick fix: proj.body.setAllowGravity(false); in the shootR and shootL (here is the link to the documentation ) functions,
And Last just add the velocity for the bullet proj.setVelocityX()
btw.: the code could be improved using classes and their properties, I would suggest looking at the phaser examples
https://phaser.io/examples/v3/view/scenes/scene-from-class and/or https://phaser.io/examples/v3/view/scenes/scene-from-es6-class on how to use classes for scene, this could remove many problems. And you would not need to use global varibales or pass so many parameters.

sprite won't collide with 2 different arrays, only one

I am currently making a small platformer game, where the player jumps up infinitely, much like the android game "Abduction". I have managed to create platforms in random locations on a timed interval and adding it to an array. However i can only get the player sprite to collide with 1 of the platform arrays, which is this.walls array that i have made so i have a set starting place for the player. Does anyone know what the issue might be.
Ugly code alert by the way, i am quite new at this.
I have checked update: function to see if i had forgot to add some stuff there. ive spellchecked the code and all sorts of things but i am at a completel loss.
var playState = {
preload: function () {
},
create: function () {
game.add.image (0, 0,'bg');
game.physics.startSystem(Phaser.Physics.ARCADE);
game.renderer.renderSession.roundPixels = true;
this.cursor = game.input.keyboard.createCursorKeys();
game.input.keyboard.addKeyCapture(
[Phaser.Keyboard.UP, Phaser.Keyboard.DOWN, Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT]);
this.wasd = {
up: game.input.keyboard.addKey(Phaser.Keyboard.W), left: game.input.keyboard.addKey(Phaser.Keyboard.A), right: game.input.keyboard.addKey(Phaser.Keyboard.D)
};
this.player = game.add.sprite(game.width/2, game.height/1.2, 'player');
this.player.anchor.setTo(0.5, 0.5);
game.physics.arcade.enable(this.player);
this.player.body.gravity.y = 800;
this.scoreLabel = game.add.text(30, 30, 'score: 0',
{ font: '18px Arial', fill: '#ffffff' });
game.global.score = 0;
game.time.events.loop(1000, this.updateScore);
game.time.events.loop(4000, this.addPlatform);
this.createWorld();
},
update: function () {
game.physics.arcade.collide(this.player, this.walls);
game.physics.arcade.collide(this.player, this.platforms);
if (!this.player.inWorld) {
this.playerDie();
}
this.movePlayer();
},
updateScore: function(){
this.score +=1;
game.global.score +=1;
//fix this at some point
},
createWorld: function() {
this.walls = [];
this.walls.push(game.add.sprite(170, 750, 'platform', 0));
this.walls.push(game.add.sprite(70, 650, 'platform', 0));
this.walls.push(game.add.sprite(320, 550, 'platform', 0));
this.walls.push(game.add.sprite(200, 450, 'platform', 0));
this.walls.push(game.add.sprite(10, 550, 'platform', 0));
this.walls.push(game.add.sprite(70, 350, 'platform', 0));
this.walls.push(game.add.sprite(310, 300, 'platform', 0));
this.walls.push(game.add.sprite(230, 200, 'platform', 0));
this.walls.push(game.add.sprite(100, 100, 'platform', 0));
this.walls.push(game.add.sprite(270, 0, 'platform', 0));
for (var x=0; x< this.walls.length; x++) {
game.physics.arcade.enable(this.walls[x]);
this.walls[x].enableBody = true;
this.walls[x].body.immovable = true;
this.walls[x].body.velocity.y = 20;
}
},
addPlatform: function() {
this.platforms = [];
this.platforms.push(game.add.sprite(game.rnd.integerInRange(0, 350),-20,'platform',0));
for (var x=0; x< this.platforms.length; x++) {
game.physics.arcade.enable(this.platforms[x]);
this.platforms[x].enableBody = true;
this.platforms[x].body.immovable = true;
this.platforms[x].body.velocity.y = 20;
}
},
movePlayer: function() {
if (this.cursor.left.isDown || this.wasd.left.isDown) {
this.player.body.velocity.x = -250;
}
else if (this.cursor.right.isDown || this.wasd.right.isDown) {
this.player.body.velocity.x = 250;
}
else {
this.player.body.velocity.x = 0;
}
if ((this.cursor.up.isDown || this.wasd.up.isDown)
&& this.player.body.touching.down){
this.player.body.velocity.y = -450;
}
},
playerDie: function() {
this.player.kill();
//this.deadSound.play();
//this.emitter.x = this.player.x;
//this.emitter.y = this.player.y;
//this.emitter.start(true, 800, null, 15);
game.time.events.add(1000, this.startMenu, this);
game.camera.shake(0.02, 300);
},
startMenu: function() {
game.state.start('menu');
},
};
this.walls is so i have a starting ground of set platforms and this.platforms is the randomly generated platforms.
I want to be able to actually jump on those platforms and not just
fall through, which i do at the moment
Your platform is an array of sprites, so you have to parse through each sprite inside your array.
Or, you can make a "Group" object, instead of plain array. You can make a Group of each plaform, then do collision with this Group and player.

How to change/update sprites textures in matterjs on clicking other object?

In my project I have some not static elements (as object1 in example) that have one sprite texture associated with them. Then I have another static element (change_sprites_object) where I want to click and change the sprites textures.
How can I achieve this in matter.js?
Example of my objects:
var x_object1 = 1370;
var y_object1 = 725;
var obj_properties = {
density: 0.0005,
frictionAir: 0.01,
restitution: 0.8,
friction: 0.01
};
var object1_properties = obj_properties;
jogo_properties.render = {
sprite: {
texture: 'images/object1.png'
}
};
object1 = Bodies.circle(x_object1, y_object1, 113, object1_properties);
change_sprites_object = Bodies.rectangle(1680, 1005, 77, 50, {
isStatic: true,
render: {
sprite: {
texture: 'images/change_sprites_object.png'
}
}
});
var flag = 0;
var element = document.getElementsByTagName('canvas')[0];
//verify if it's a click or drag
element.addEventListener("mousedown", function () {
flag = 0;
}, false);
element.addEventListener("mousemove", function () {
flag = 1;
}, false);
element.addEventListener("mouseup", function () {
if (flag === 0) {
var mouse = mouseConstraint.mouse;
if (Bounds.contains(change_sprites_object.bounds, mouse.position) {
//change object1 sprite
}...

Categories