How to prevent objects to jump off platforms? - javascript

I have a game set up like this:
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {preload: preload, create: create, update: update});
var platforms;
var aGroup;
function preload() {
game.load.image('platform', 'img/platform.png');
game.load.image('a', 'img/a.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
platforms = game.add.group();
platforms.enableBody = true;
var platform = platforms.create(100, 100, 'platform');
aGroup = game.add.group();
aGroup.enableBody = true;
platforms.forEach(function(item) {
item.body.immovable = true;
aGroup.create(item.x, item.y - 32, 'a');
}, this);
aGroup.forEach(function(a) {
a.body.velocity.x = 100;
}
}
function update() {
game.physics.arcade.collide(aGroup, platforms);
aGroup.forEach(function(a) {
if(a.body.blocked.right) {
a.body.velocity.x = -100;
}
else if(a.body.blocked.left) {
a.body.velocity.x = 100;
}, this);
}
}
Currently I can check if a is colliding with the world boundaries and if it does it changes direction. Right now when a reaches the end of the platform it just falls down. I want a to change direction when it reaches the end of the platform.
How can I do it?

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>

HTML5 game not working - phaser.js

Basic rundown:
I am developing the game via JS with the aid of [howlerjs.com] for audio and [phaser.io] for the graphics and physics. The game is hosted at [ygdqe.co.nf]. The code I currently have is [main.js], [index.html], [phaser.js] and [howler.js] and they can all be found in the root of the domain. My main problem is when loading the [index.html] - which has links to all the mentioned js - it just shows a blank page.
Just to mention, I currently do not have a laptop so I have loaded all the code in chrome on IOS.
Links:
[phaser.js]:http://ygdqe.co.nf/phaser.js
[main.js]:http://ygdqe.co.nf/main.js
[howlerjs.com]:https://github.com/goldfire/howler.js
[phaser.io]:https://phaser.io
[ygdqe.co.nf]:http://ygdqe.co.nf
[howler.js]:http://ygdqe.co.nf/howler.js
[index.html]:http://ygdqe.co.nf/index.html
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'KABOOMSSS', { preload: preload, create: create, update: update });
function preload() {
game.stage.backgroundColor = '#85b5e1';
game.load.crossOrigin = 'anonymous';
game.load.image('player', 'phaser-dude.png');
game.load.image('platform', 'platform.png');
}
var player;
var platforms;
var cursors;
var jumpButton;
var xtime;
function create() {
var xtime = 0;
player = game.add.sprite(100, 200, 'player');
game.physics.arcade.enable(player);
player.body.collideWorldBounds = true;
player.body.gravity.y = 500;
platforms = game.add.physicsGroup();
platforms.create(500, 150, 'platform');
platforms.create(-200, 300, 'platform');
platforms.create(400, 450, 'platform');
platforms.setAll('body.immovable', true);
cursors = game.input.keyboard.createCursorKeys();
jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
game.input.onTap.add(onTap, this);
var sound = new Howl({
src: ['http://soundimage.org/wp-content/uploads/2016/11/Automation.mp3']
});
function onTap () {
if (xtime == 0) {
} else if (xtime != 0) {
sound.play;
}
var xtime = (xtime + 1);
}
function update () {
game.physics.arcade.collide(player, platforms);
player.body.velocity.x = 0;
if (cursors.left.isDown)
{
player.body.velocity.x = -250;
}
else if (cursors.right.isDown)
{
player.body.velocity.x = 250;
}
if (jumpButton.isDown)
{
player.body.velocity.y = -400;
}
}
function render () {
}

Phaser: Key Down + Collision Kill

Forewarning: semi-newbie
Basically, if the user has the left cursor down and a "token" collides with the lftRect, I want to kill the token. For some reason my kill callback function for the collision is not working (below is relevant code):  
gumballGoGo.Preloader = function(game){
this.player = null;
this.ground = null;
//this.tokens = null;
this.ready = false;
};
var cursors, lftInit, rghtInit, ground, testDrp, sprite, tokens, rect, lftRect, ctrRect, rghtRect, lftToken;
var total = 0;
function lftHit(lftRect, lftToken) {
if ( lftInit == true ){
lftToken.kill()
}
};
gumballGoGo.Preloader.prototype = {
preload: function(){
},
create: function() {
// LFT BOX
lftRect = this.add.sprite(0, this.world.height - 150, null);
this.physics.enable(lftRect, Phaser.Physics.ARCADE);
lftRect.body.setSize(100, 100, 0, 0);
// CNTR BOX
ctrRect = this.add.sprite(100, this.world.height - 150, null);
this.physics.enable(ctrRect, Phaser.Physics.ARCADE);
ctrRect.body.setSize(100, 100, 0, 0);
// RGHT BOX
rghtRect = this.add.sprite(200, this.world.height - 150, null);
this.physics.enable(rghtRect, Phaser.Physics.ARCADE);
rghtRect.body.setSize(100, 100, 0, 0);
// INIT TOKEN GROUP
tokens = this.add.group();
tokens.enableBody = true;
this.physics.arcade.enable(tokens);
testDrp = tokens.create(125, -50, 'token');
testDrp.body.gravity.y = 300;
// CONTROLS
this.cursors = this.input.keyboard.createCursorKeys();
},
update: function() {
this.ready = true;
if (this.cursors.left.isDown)
{
lftInit = true;
}
else if (this.cursors.right.isDown)
{
rghtInit = true;
}
else
{
lftInit, rghtInit = false;
}
if (total < 20)
{
tokenSpawn();
}
this.physics.arcade.collide(lftRect, lftToken, lftHit, null, this);
}
};
function tokenSpawn() {
lftToken = tokens.create(25, -(Math.random() * 800), 'token');
lftToken.body.gravity.y = 300;
total++;
}
The ultimate goal is to recreate this type of gameplay. 
One additional note: as of now I am dropping "tokens" using a random spawn loop. I'd rather use a timed patter for the token drop. If you have any advice on that please share as well. Thanks :]
Not sure, so this is a guess, but you're applying the last parameter of 'this' to the function 'lfthit' that is outside of the gumballGoGo.Preloader.prototype object. What error are you getting in the console?

Adding a Tiled map to Phaser and issues with character changing facing

I've created a Tiled map for a game I'm making in Phaser and despite following a tutorial, I can't seem to get it to load. I'm making the game in javascript using webstorm. The naming of everything seems ok and I'm getting no error pop ups but it's loading only a black background instead of the map.
var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', { preload: preload, create: create, update: update });
function preload() {
game.load.spritesheet('player', 'res/player_strip8.png', 80 , 190);
game.load.spritesheet('player-right', 'res/player_right.png');
game.load.spritesheet('player-left', 'res/player_left.png');
game.load.tilemap('map', 'res/Game_map.json', null, Phaser.Tilemap.TILED_JSON);
game.load.image('tiles', 'res/back-ground.png');}
var map;
var tileset;
var layer;
var player;
var facing = 'left';
function create() {
map = game.add.tilemap('map');
//game.stage.backgroundColor = '#00FFFF';
game.physics.startSystem(Phaser.Physics.ARCADE);
players = game.add.group();
players.enableBody = true;
createPlayer("");
map.addTilesetImage('Back-ground', 'tiles');
groundLayer = map.createLayer('GroundLayer');
Cursors = game.input.keyboard.createCursorKeys();
}
function update() {
playerUpdate();
}
function createPlayer(x,y){
var player = players.create(0,0,'player-right');
player.body.bounce.y = 0.5;
player.body.gravity.y = 300;
player.body.collideWorldBounds = true;
}
function playerUpdate(){
game.physics.arcade.collide(players, players);
players.forEach(function (p) {
p.body.velocity.x = 0;
if(Cursors.left.isDown){
//players.create('player-left');
//players.animation('left')
p.body.velocity.x = -150;
//player = players.create(0,0,'player-left');
} else if (Cursors.right.isDown){
//players.create('player-right');
//players.animation('right')
p.body.velocity.x = 150
// player = players.create(0,0,'player-right');
}
if (Cursors.up.isDown && p.body.touching.down ){
p.body.velocity.y = -350
}
})
}
function createPlatform() {
}

Phaser - Implementing states / changing active script

Sorry if this is the wrong place to put this, I haven't had much luck anywhere else unfortunately.
In Phaser I have made a tilemap and a player sprite, this all works perfectly using P2 physics. I have a door way in my tilemap which when I enter I want a different script to run, changing the current tilemap to a different one and moving the player's position accordingly.
I already have a basic if statement that checks if the player's position is within the range of the door and console logs, that works fine.
Code:
var game = new Phaser.Game(560, 560, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });
function preload() {
game.load.tilemap('tilemap', 'assets/tilemaps/test.json', null, Phaser.Tilemap.TILED_JSON);
game.load.image('tiles', 'assets/tilemaps/tileset.png');
game.load.image('player', 'assets/images/player.png');
}
var player;
var cursors;
var map;
var layer;
function create() {
map = game.add.tilemap('tilemap');
map.addTilesetImage('basic', 'tiles');
layer = map.createLayer('Background');
layer2 = map.createLayer('Walls');
layer.resizeWorld();
game.physics.startSystem(Phaser.Physics.P2JS);
game.physics.p2.setBoundsToWorld(true, true, true, true, false);
map.setCollision(1, true, "Walls");
game.physics.p2.convertTilemap(map, "Walls");
player = game.add.sprite(game.world.centerX, game.world.centerY, 'player');
game.physics.p2.enable(player);
player.body.fixedRotation = true;
player.body.clearShapes();
player.body.addRectangle(20, 0, 0, 0);
cursors = game.input.keyboard.createCursorKeys();
game.camera.follow(player);
//player.body.debug = true;
}
function update() {
player.body.setZeroVelocity();
if (cursors.up.isDown)
{
player.body.moveUp(300)
}
else if (cursors.down.isDown)
{
player.body.moveDown(300);
}
if (cursors.left.isDown)
{
player.body.velocity.x = -300;
}
else if (cursors.right.isDown)
{
player.body.moveRight(300);
}
if (player.x > 248 && player.x < 311 && player.y < 25)
{
console.log("Door opened");
}
}
function render() {
game.debug.cameraInfo(game.camera, 32, 32);
game.debug.spriteCoords(player, 32, 500);
}

Categories