Search the Community

Showing results for tags 'states'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • HTML5 Game Coding
    • News
    • Game Showcase
    • Coding and Game Design
  • Frameworks
    • Phaser
    • Pixi.js
    • Babylon.js
    • Panda 2
    • melonJS
    • Haxe JS
    • Kiwi.js
  • General
    • General Talk
  • Business
    • Collaborations (un-paid)
    • Jobs (Hiring and Freelance)
    • Services Offered

Found 62 results

  1. Multiple levels

    I Just finished the beginners "Making your first game" tutorial. I'm a student and I want to integrate phaser into my final project, but have never used it before This is my second day and I currently am confused about how to make multiple levels by implementing states. Basically I want the player to reach a certain object in the game and when they interact I want the level to change to the next level. I would like to be able to call this.state.start('level_two'); once the object has been reached. I am just confused on how to do a basic set up of states. Any advice or direction?
  2. Global key event in all states

    Hey there, I'm trying to get a key to always call a certain function, regardless of which state my game is in. At the moment, my code is this: var escKey = null BasicGame.Boot = function (game) { //... }; BasicGame.Boot.prototype = { init: function () { escKey = game.input.keyboard.addKey(Phaser.Keyboard.ESC); escKey.onDown.add(function(){console.log("esc")}, game); } And so on. escKey stays defined in all states, but onDown doesn't trigger. If I move the two lines within init to a state, I can use ESC in that state, but not in any state after that. Is there a way to do this?
  3. Same background image in all states

    Hello, I'm new to the Phaser framework and I'm trying to have a single backgound and logo througout all the states in a phaser game. I add the background image in the very first state but when I start the next state using: this.game.state.start("State2"); the background image disappears. Do I have to load the background image in every state? Thanks
  4. Hello, I'm using Phaser for a school project. were making a 2d platformer game. I have multiple states for different levels. The transition works fine, next level is displayed properly, enemies function as the should, everything scrolls, but the keyboard stops recognizing input. right now i have: this.cursors = this.input.keyboard.createCursorKeys(); in the create function of both Level.js and Level2.js but they are not working for level 2. i have also modified the create cursor keys function in phaser.js to add a few key codes so now it reads like this: return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT, 'ctrl':Phaser.KeyCode.CONTROL, 'shift':Phaser.KeyCode.SHIFT, 'alt':Phaser.KeyCode.ALT, 'enter':Phaser.KeyCode.ENTER}); Basically wondering what i should be doing different to get keyboard input recognized in multiple states. i tried doing the game.input.resetLocked=true; in the create functions of either level.js or level2.js, it either did nothing (for level2) or stopped the game from running (for level1)
  5. Ajax callback in Phaser using states

    Hey everybody, excuse my poor english ! I was using a single JS file for my program structured like this : index.html with <div id="timediv"></div> script.js with my Phaser code including anim function called in ajax.js. This function was declared after the update in script.js. ajax.js with function refreshdiv() which call lance() which call anim() every 60 seconds. Everything was ok like this Now I want to use states. I made : bootState, loadState and the main state called scriptState. But where do I have to place anim() declaration now ? I tried different places (in scriptState, after update, in create, in update, in bootState init etc...) but I have always the same message : Thanks a lot for your help !
  6. Phaser Kill freezing game

    Hi I have an issue in my game.js these are snippets from the entire code where bullets and enemies overlap, but when they overlap the game crashes?: create : function(){ this.enemies = game.add.group(); this.enemies.enableBody = true; for (var i = 0; i < 1; i++) { var s = this.enemies.create(game.world.randomX, game.world.randomY, 'enemy1'); s.name = 'enemy1' + s; s.body.collideWorldBounds = true; s.body.bounce.setTo(0.1, 0.1); s.animations.add('walk', [0, 1,]); s.play('walk', 6, true); s.body.velocity.setTo(5 + Math.random() * 40, 5 + Math.random() * 40); } { var f = this.enemies.create(game.world.randomX, game.world.randomY, 'enemy2'); f.name= 'enemy2' + f; f.body.collideWorldBounds = true; f.body.bounce.setTo(0.1, 0.1); f.animations.add('walk', [0, 1,]); f.play('walk', 6, true); f.body.velocity.setTo(5 + Math.random() * 40, 5 + Math.random() * 40); } } update: function() { game.physics.arcade.overlap(this.bullet, this.enemies, this.enemyKill, null, this); enemyKill: function(){ this.enemies.kill(); this.score += 10; this.scoreText.text = 'score: ' + score; }, Thanks
  7. Phaser States Player Animation Problem

    Hi All i was wondering if someone could help me with a phaser state query. I have been learning phaser from phaser.io and its all for a html index file however the code seems to be different then to what i need if i was to build a game with states. For example i have a player walking animation but converting it for js states seems to be very difficult, i cannot find a tutorial anywhere. Any chance someone could point me in the right direction? happy to share the code Thanks
  8. Our game is a runner, which has portals that sends you to a different time period and place when you run into them. I've made it so when you get in a portal, the code goes from one state to the other and create the world over again with different textures. But I have this issue that the player gets super speed after the portal. Like, I can run 10000px in the matter of 2 seconds speed. I have not been able to find out why so far, but with a couple of console logs I've notice both the old state and then new state updates are both running. So thought removing the run function in the new world state would work, but didn't make a difference This is the PlayState that the game starts in after you click play. var cursors; var playState = { create: function() { console.log("Play kjørte"); var mapLen = 10000; // Velg lengden av banen (i pixler) var posX = 0; // Make game here game.physics.startSystem(Phaser.Physics.ARCADE); game.world.setBounds(0, 0, mapLen, 600); bg = game.add.sprite(mapLen/2, 300, "sky"); bg.scale.setTo(1,1); bg.anchor.setTo(0.5,0.5); platforms = game.add.group(); platforms.enableBody = true; while (true) { var ground = platforms.create(posX, 535,"ground"); ground.scale.setTo(1,1); ground.anchor.setTo(0,0) ground.body.immovable = true; posX += 150; if (posX > mapLen) { console.log("posX mer enn mapLen, avbryt laging av ground"); break; } } player = game.add.sprite(100, 500, "character"); player.anchor.setTo(0.5, 0.5); player.scale.setTo(1,1); game.camera.follow(player); game.physics.arcade.enable(player); player.body.gravity.y = 800; player.body.collideWorldBounds = true; player.animations.add("right",[0,1,2,3,4,5], 16, true); player.animations.add("jumpRight",[2], 1, true); player.animations.add("jumpLeft",[0], 1, true); player.animations.add("left",[0], 20, true); enemies = game.add.group(); enemy = game.add.sprite(8000, 505, "umbrellaGirl"); enemy.anchor.setTo(0.5, 0.5); game.physics.arcade.enable(enemy); portal = game.add.sprite(600, 500, "portal"); portal.anchor.setTo(0.5,0.5); portal.scale.setTo(0.8,0.8); game.physics.arcade.enable(portal); tBuilding = game.add.sprite(9700, 535, "targetBuilding"); tBuilding.anchor.setTo(0, 1); tBuilding.scale.setTo(0.8,0.8); game.physics.arcade.enable(tBuilding); var timer; timer = setInterval(this.run, 10); cursors = game.input.keyboard.createCursorKeys(); }, run: function() { //console.log("run kjørte"); player.body.velocity.x = 520; }, //Function to make camera follow character lockonFollow: function() { game.camera.follow(player, Phaser.Camera.FOLLOW_LOCKON); style = 'STYLE_LOCKON'; }, update: function() { // code to for example, kill, move player and jump game.physics.arcade.collide(player,platforms); game.physics.arcade.overlap(tBuilding, player, this.win, null); player.body.velocity.x = 0; if (game.physics.arcade.collide(enemy, player)) { player.kill(); game.state.start("lose"); } if (game.physics.arcade.collide(portal, player)) { this.game = null; this.state.start("ancientGreece",true, false); } //if (cursors.right.isDown) { if (player.body.touching.down){ player.animations.play("right"); } //} else if (cursors.left.isDown) { player.body.velocity.x = -400; if (player.body.touching.down){ player.animations.play("left"); } } else { player.animations.stop(); player.frame = 12; } // Jump if (cursors.up.isDown && player.body.touching.down) { player.body.velocity.y = -400; player.animations.play("jumpRight"); if (cursors.up.isDown && cursors.left.isDown) { player.animations.play("jumpLeft"); } } }, win: function() { game.state.start("win"); //"win" was an invisible sprite the player collided with to trigger the jump to win.js }, } And this is the state where the world textures become Ancient Greece textures (after you hit the portal). var cursors; var greeceState = { create: function() { console.log("Greece kjørte"); var mapLen = 10000; // Velg lengden av banen (i pixler) var posX = 0; var timer; //game.physics.startSystem(Phaser.Physics.ARCADE); //game.world.setBounds(0, 0, mapLen, 600); bg = game.add.sprite(mapLen/2, 300, "sky"); bg.scale.setTo(1,1); bg.anchor.setTo(0.5,0.5); platforms = game.add.group(); platforms.enableBody = true; while (true) { var ground = platforms.create(posX, 535,"groundSand"); ground.scale.setTo(1,1); ground.anchor.setTo(0,0) ground.body.immovable = true; posX += 150; if (posX > mapLen) { console.log("posX mer enn mapLen, avbryt laging av ground"); break; } } player = game.add.sprite(100, 500, "character"); player.anchor.setTo(0.5, 0.5); player.scale.setTo(1,1); game.camera.follow(player); game.physics.arcade.enable(player); player.body.gravity.y = 800; player.body.collideWorldBounds = true; player.animations.add("right",[0,1,2,3,4,5], 16, true); //timer = setInterval(this.run, 0.10); cursors = game.input.keyboard.createCursorKeys(); }, /* run: function() { console.log("run kjørte"); //player.body.velocity.x = 520; },*/ update: function() { //console.log("update Greece"); // code to for example, kill, move player and jump game.physics.arcade.collide(player,platforms); game.physics.arcade.overlap(tBuilding, player, this.win, null); //player.body.velocity.x = 0; if (player.body.touching.down){ player.animations.play("right"); } /* if (player.body.position.x > 9000) { game.state.start("play"); }*/ } } My apologies if I could snip the code down a little, I wasn't sure what would be relevant to show or not with the issue I have. The game looks like this before and after portal: DemolitionDavid.rar
  9. Classes, Sprite Keys etc.

    Hi there! I'm new around here, and I'm quite new to JS and especially Phaser. I did a little bit of AS3 a few years back but I'm still pretty rusty, so right now I'm not really able to pull off what I have in mind. I hope you guys can help me out a bit! So, first things first, I am using a multi-state, multi-file-structure to keep it clean. I have succeeded in writing two classes which both have their own file, expanding Sprite and Group. This here is the constructor for the Class that uses Group, nothing fancy. Board = function (game) { Phaser.Group.call(this, game); }; Board.prototype = Object.create(Phaser.Group.prototype); Board.prototype.constructor = Board; Board.prototype.update = function() { }; 1. My first Problem is this: In this class, I have a function that is supposed to add Sprites to the Group in a specific manner: Board.prototype.build = function(Board_plan) { for (var i=0; i < 3; i++) { for (var ii=0; ii < Board_plan[1].length; ii++) { sprite = this.create(ii*100, i*140, 'board_blank'); } } }; In my preloader state, I load board_blank, and I'm able to use it in my main State without problems. When I create a new "Board" and then use this function, I get "Uncaught TypeError: Cannot read property 'getImage' of undefined" though. If I don't give a Sprite to the function and let it use the default, it works like a charm. I tried to retrieve the Sprite via cache (providing game to the function, then game.cache.getImage), didn't work either. So, how can I access my Sprite key from within extzernal classes or make them global or something? 2. Here's another one: The Sprite Class I mentioned earlier is meant for a certain type of game objects that I want to keep throughout my states. It carries a number of variables with specific values for each instance I'm creating. A bit like characters with different stats, which can be changed at any time and should therefore not be cleared ever. I understand that I have to instanciate them as global, which works so far. The problem is, if I add them to existing in one state, then switch to the next, my global variable is empty, I suppose because all sprites are cleared at the end of a state? So how would I solve this? Would It maybe be a better Idea to not expand Sprite, but also Group instead and then just add new instances of sprites on demand instead of relying on a single "base sprite"? There's more, but I think that's enough for now I appreciate for any help! Thank you!
  10. Hello All, I apologize in advance for the wall of code. Also, thanks in advance to anyone who is willing to take a crack at this. I'm having a very specific issue which I am guessing is an issue with my implementation and not the library. I am using Phaser Editor with Phaser CE as my framework. Last week I began working in prefabs into my game using extended sprites as per this example. The prefabs are separate scripts which are included in index.html. Everything has worked well except for a peculiar bug which is that when my player prefab overlaps a group which is being checked by arcade.overlap the player's body.touching is flagged as true. Because a check for touching.down is the prerequisite for jumping it means my player can effectively fly whenever overlapping. Collision appears to be working as expected and I can even use collision callbacks. The same groups that cause issues do not flag body.touching if they are not being checked for overlap. I believe the issues is because the groups are created by the editor and that the player prefab as a separate .js file does not have a handle on them but I'm not sure. I guess I have gotten myself in over my head with this approach but I feel like I am so close to getting it I am really hesitant to start over with a more monolithic approach. Here is the code for the level state which calls the script generated by the editor and the player prefab. Hope this all makes sense. Level State /** * level state. */ function Level() { Phaser.State.call(this); // TODO: generated method. } /** @type Phaser.State */ var proto = Object.create(Phaser.State.prototype); Level.prototype = proto; Level.prototype.constructor = Level; Level.prototype.init = function() { this.physics.startSystem(Phaser.Physics.ARCADE); this.world.resize(2000, 500); this.world.setBounds(0, 0, 2000, 500); this.physics.arcade.gravity.y = 800; }; Level.prototype.preload = function() { this.load.pack("levels", "assets/assets-pack.json"); this.game.load.atlas('HUD', 'assets/atlas/HUD.png', 'assets/atlas/HUD.json', Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); }; Level.prototype.create = function() { this.game.renderer.setTexturePriority(['Forest_BG', 'Forest_Tiles', 'forestStage', 'characters', 'objects', 'HUD']); this.scene = new level1(this.game); this.scene.coordTimer = 0; this.scene.fTokens.forEach(this.convert, this); this.game.camera.follow(this.scene.player, Phaser.Camera.FOLLOW_PLATFORMER); //HUD this.scene.XP = new xp(this.game, 6, 6); this.game.add.existing(this.scene.XP); this.scene.fHUD.add(this.scene.XP); this.scene.XP.fixedToCamera = true;this.scene.XP.cameraOffset.setTo(6, 6); this.scene.HUDBase = this.game.add.sprite(2, 2, 'HUD', 'base'); this.scene.fHUD.add(this.scene.HUDBase); this.scene.HUDBase.fixedToCamera = true;this.scene.HUDBase.cameraOffset.setTo(2, 2); this.scene.healthBar = new healthBar(this.game, 39, 6); this.game.add.existing(this.scene.healthBar); this.scene.fHUD.add(this.scene.healthBar); this.scene.healthBar.fixedToCamera = true;this.scene.healthBar.cameraOffset.setTo(39, 6); this.scene.energyBar = new energyBar(this.game, 39, 16); this.game.add.existing(this.scene.energyBar); this.scene.fHUD.add(this.scene.energyBar); this.scene.energyBar.fixedToCamera = true;this.scene.energyBar.cameraOffset.setTo(39, 16); this.scene.magicBar = new magicBar(this.game, 39, 26); this.game.add.existing(this.scene.magicBar); this.scene.fHUD.add(this.scene.magicBar); this.scene.magicBar.fixedToCamera = true;this.scene.magicBar.cameraOffset.setTo(39, 26); // set the physics properties of the normal collision sprites this.scene.fCollisionLayer.setAll("body.immovable", true); this.scene.fCollisionLayer.setAll("body.allowGravity", false); // hide all objects of the normal collision layer this.scene.fCollisionLayer.setAll("renderable", false); // set the physics properties of the oneWay collision sprites this.scene.fOneWay.setAll("body.immovable", true); this.scene.fOneWay.setAll("body.allowGravity", false); // hide all objects of the oneWay collision layer this.scene.fOneWay.setAll("renderable", false); // disable all but top down collision this.scene.fOneWay.setAll("body.checkCollision.down", false); this.scene.fOneWay.setAll("body.checkCollision.left", false); this.scene.fOneWay.setAll("body.checkCollision.right", false); // set the physics properties of cliff this.scene.fCliff.setAll("body.immovable", true); this.scene.fCliff.setAll("body.allowGravity", false); // hide all objects of cliff this.scene.fCliff.setAll("renderable", false); // set the physics properties of waterLayer this.scene.fWaterLayer.setAll("body.immovable", true); this.scene.fWaterLayer.setAll("body.allowGravity", false); // hide all objects of cliff this.scene.fWaterLayer.setAll("renderable", false); // set the physics properties of airLayer this.scene.fAirLayer.setAll("body.immovable", true); this.scene.fAirLayer.setAll("body.allowGravity", false); // hide all objects of cliff this.scene.fAirLayer.setAll("renderable", false); this.scene.fTokens.setAll("renderable", false); this.scene.fPickups.setAll("body.allowGravity", false); //Water Effects if (this.scene.waterPresent) { this.add.tween(this.scene.fWater).to({ x : this.scene.fWater.x + 32 }, 2000, "Linear", true, 0, -1, true); var delay = 0; for (var i = 0; i < 60; i++) { var bbls = this.game.add.sprite(-100 + (this.game.world.randomX), this.scene.stageBottom, 'Forest_Tiles', 'bubble.png'); bbls.scale.set(this.game.rnd.realInRange(0.1, 1.5)); var speed = this.game.rnd.between(2000, 4000); this.game.add.tween(bbls).to({ y: this.scene.waterLevel }, speed, Phaser.Easing.Sinusoidal.InOut, true, delay, 1000, false).onComplete.add(bbls.kill, bbls); delay += 200; } } }; Level.prototype.update = function() { this.scene.fBgNear.x= this.game.camera.x*0.4; this.scene.fBgFar.x= this.game.camera.x*0.6; this.physics.arcade.collide(this.scene.player, this.scene.fCollisionLayer); this.physics.arcade.collide(this.scene.player, this.scene.fOneWay); //if (this.physics.arcade.collide(this.scene.player, this.scene.fOneWay)) this.physics.arcade.collide(this.scene.fEnemies, this.scene.fCollisionLayer); this.physics.arcade.collide(this.scene.fEnemies, this.scene.fOneWay); this.game.physics.arcade.collide(this.scene.player, this.scene.fEnemies, this.collisionCallback, this.enemyCollide, this); this.game.physics.arcade.collide(this.scene.fCliff, this.scene.fEnemies, this.collisionCallback, this.enemyCliff, this); this.physics.arcade.overlap(this.scene.player, this.scene.fPickups, this.pickup, null, this); this.physics.arcade.overlap(this.scene.player.attack, this.scene.fEnemies, this.enemyHit, null, this); this.physics.arcade.overlap(this.scene.fObjects, this.scene.fWaterLayer, this.underWater, null, this); //this.physics.arcade.overlap(this.scene.fObjects, this.scene.fAirLayer, //this.aboveWater, null, this); if (this.game.time.now > this.scene.coordTimer) { this.game.lPlayerX = this.scene.player.x; this.game.lPlayerY = this.scene.player.y; this.scene.coordTimer = this.game.time.now + 200; } }; Level.prototype.convert = function(sprite) { this.scene.pF = {}; var data = sprite.data; var x = sprite.x; var y = sprite.y; var prefab = data.prefab; if (prefab === Player) { this.scene.player = new prefab(this.game, x, y); this.game.add.existing(this.scene.player); this.scene.fPlayers.add(this.scene.player); } else { this.scene.pF[prefab + x + y] = new prefab(this.game, x, y); this.game.add.existing(this.scene.pF[prefab + x + y]); if (data.group === 'pickups') { this.scene.fPickups.add(this.scene.pF[prefab + x + y]); } else if (data.group === 'enemies') { this.scene.fEnemies.add(this.scene.pF[prefab + x + y]); } else { this.scene.fObjects.add(this.scene.pF[prefab + x + y]); } } }; Level.prototype.pickup = function(player, pickup) { pickup.body.enable = false; pickup.effect(); this.add.tween(pickup).to({ y : pickup.y - 16 }, 1000, "Expo.easeOut", true); this.add.tween(pickup.scale).to({ x : 1.25, y : 1.25 }, 1000, "Linear", true); this.add.tween(pickup).to({ alpha : 0.2 }, 1000, "Linear", true).onComplete.add(pickup.kill, pickup); }; Level.prototype.enemyCollide = function(player, enemy){ player.hurt(enemy.attack); return true; }; Level.prototype.enemyCliff = function(cliff, enemy){ enemy.cliff(); }; Level.prototype.enemyHit = function(weapon, enemy){ enemy.hurt(weapon.attack); }; Level.prototype.underWater = function(object, water){ object.tint = 0x5fcde4; }; Level.prototype.aboveWater = function(object, water){ object.tint = 0xffffff; }; Level 1 Scene (Generated by Phaser Editor) // Generated by Phaser Editor v1.2.1 /** * level1. * @param {Phaser.Game} aGame The game. * @param {Phaser.Group} aParent The parent group. If not given the game world will be used instead. */ function level1(aGame, aParent) { Phaser.Group.call(this, aGame, aParent); /* --- pre-init-begin --- */ // you can insert code here /* --- pre-init-end --- */ var bgFar = this.game.add.group(this); this.game.add.sprite(0, 0, 'Forest_BG', 'bg1_far', bgFar); this.game.add.sprite(528, 0, 'Forest_BG', 'bg1_far', bgFar); this.game.add.sprite(1056, 0, 'Forest_BG', 'bg1_far', bgFar); this.game.add.sprite(1584, 0, 'Forest_BG', 'bg1_far', bgFar); var bgNear = this.game.add.group(this); this.game.add.sprite(0, 0, 'Forest_BG', 'bg1_near', bgNear); this.game.add.sprite(528, 0, 'Forest_BG', 'bg1_near', bgNear); this.game.add.sprite(1056, 0, 'Forest_BG', 'bg1_near', bgNear); this.game.add.sprite(1584, 0, 'Forest_BG', 'bg1_near', bgNear); var airLayer = this.game.add.physicsGroup(Phaser.Physics.ARCADE, this); this.game.add.tileSprite(0, 0, 2208, 272, 'Forest_Tiles', 'air.png', airLayer); this.game.add.sprite(0, 0, 'forestStage', 'level1_stage', this); var water = this.game.add.group(this); this.game.add.sprite(1824, 288, 'forestStage', 'waterTile', water); this.game.add.sprite(1360, 288, 'forestStage', 'waterTile', water); this.game.add.sprite(896, 288, 'forestStage', 'waterTile', water); this.game.add.sprite(432, 288, 'forestStage', 'waterTile', water); this.game.add.sprite(-32, 288, 'forestStage', 'waterTile', water); var waterLayer = this.game.add.physicsGroup(Phaser.Physics.ARCADE, this); this.game.add.tileSprite(-31, 296, 2237, 198, 'Forest_Tiles', 'liquid.png', waterLayer); var obstacles = this.game.add.group(this); this.game.add.sprite(167, 230, 'Forest_Tiles', 'box.png', obstacles); this.game.add.sprite(167, 242, 'Forest_Tiles', 'box.png', obstacles); this.game.add.sprite(156, 242, 'Forest_Tiles', 'box.png', obstacles); var oneWay = this.game.add.physicsGroup(Phaser.Physics.ARCADE, this); this.game.add.sprite(431, 90, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(392, 87, 64, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(375, 102, 66, 34, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(343, 184, 33, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(280, 200, 82, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(70, 150, 38, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(97, 118, 24, 36, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(56, 103, 49, 51, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.sprite(152, 119, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(183, 165, 17, 40, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(165, 200, 36, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(352, 256, 224, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(158, 244, 23, 12, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(169, 232, 12, 24, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(16, 256, 176, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(768, 272, 64, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(912, 160, 272, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(762, 216, 29, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(821, 167, 36, 16, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.sprite(791, 136, 'Forest_Tiles', 'one-way.png', oneWay); this.game.add.tileSprite(624, 272, 64, 16, 'Forest_Tiles', 'one-way.png', oneWay); var objects = this.game.add.group(this); var players = this.game.add.group(objects); var enemies = this.game.add.group(objects); var pickups = this.game.add.physicsGroup(Phaser.Physics.ARCADE, objects); var tokens = this.game.add.group(this); var coin1 = this.game.add.sprite(96, 224, 'objects', 'coin11', tokens); coin1.data = { prefab: Coin1, group : 'pickups' }; var snakeGreen0 = this.game.add.sprite(131, 224, 'characters', 'snakeGreen0', tokens); snakeGreen0.data = { prefab : greenSnake, group : 'enemies' }; var hPotion10 = this.game.add.sprite(301, 169, 'objects', 'hPotion10', tokens); hPotion10.data = { prefab : hPotion, group : 'pickups' }; var hPotion101 = this.game.add.sprite(187, 137, 'objects', 'hPotion10', tokens); hPotion101.data = { prefab : hPotion, group : 'pickups' }; var hPotion102 = this.game.add.sprite(442, 239, 'objects', 'hPotion10', tokens); hPotion102.data = { prefab : hPotion, group : 'pickups' }; var snakeGreen01 = this.game.add.sprite(474, 224, 'characters', 'snakeGreen0', tokens); snakeGreen01.data = { prefab : greenSnake, group : 'enemies' }; var snakeGreen011 = this.game.add.sprite(514, 223, 'characters', 'snakeGreen0', tokens); snakeGreen011.data = { prefab : greenSnake, group : 'enemies' }; var snakeGreen012 = this.game.add.sprite(376, 223, 'characters', 'snakeGreen0', tokens); snakeGreen012.data = { prefab : greenSnake, group : 'enemies' }; var hPotion1021 = this.game.add.sprite(624, 256, 'objects', 'hPotion10', tokens); hPotion1021.data = { prefab : hPotion, group : 'pickups' }; var player = this.game.add.sprite(32, 224, 'characters', 'gunther0', tokens); player.data = { prefab : Player }; var snakeGreen013 = this.game.add.sprite(656, 240, 'characters', 'snakeGreen0', tokens); snakeGreen013.data = { prefab : greenSnake, group : 'enemies' }; var snakeGreen0131 = this.game.add.sprite(768, 240, 'characters', 'snakeGreen0', tokens); snakeGreen0131.data = { prefab : greenSnake, group : 'enemies' }; var snakeGreen01311 = this.game.add.sprite(928, 128, 'characters', 'snakeGreen0', tokens); snakeGreen01311.data = { prefab : greenSnake, group : 'enemies' }; var snakeGreen01312 = this.game.add.sprite(1056, 128, 'characters', 'snakeGreen0', tokens); snakeGreen01312.data = { prefab : greenSnake, group : 'enemies' }; var hPotion10211 = this.game.add.sprite(1040, 144, 'objects', 'hPotion10', tokens); hPotion10211.data = { prefab : hPotion, group : 'pickups' }; var collisionLayer = this.game.add.physicsGroup(Phaser.Physics.ARCADE, this); this.game.add.tileSprite(0, -16, 16, 496, 'Forest_Tiles', 'collision.png', collisionLayer); this.game.add.tileSprite(0, 480, 2000, 16, 'Forest_Tiles', 'collision.png', collisionLayer); var cliff = this.game.add.physicsGroup(Phaser.Physics.ARCADE, this); this.game.add.tileSprite(576, 240, 2, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.tileSprite(352, 240, 2, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.tileSprite(192, 240, 1, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.tileSprite(622, 256, 2, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.tileSprite(768, 256, 3, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.tileSprite(830, 256, 2, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.tileSprite(910, 144, 3, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.tileSprite(1183, 144, 3, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.tileSprite(685, 256, 2, 16, 'Forest_Tiles', 'cliff.png', cliff); this.game.add.sprite(0, 0, 'forestStage', 'level1_foreground', this); var HUD = this.game.add.group(this); // public fields this.fBgFar = bgFar; this.fBgNear = bgNear; this.fAirLayer = airLayer; this.fWater = water; this.fWaterLayer = waterLayer; this.fObstacles = obstacles; this.fOneWay = oneWay; this.fObjects = objects; this.fPlayers = players; this.fEnemies = enemies; this.fPickups = pickups; this.fTokens = tokens; this.fCollisionLayer = collisionLayer; this.fCliff = cliff; this.fHUD = HUD; /* --- post-init-begin --- */ //Level Paramaters this.waterPresent = true; this.waterLevel = 296; this.stageBottom = 480; /* --- post-init-end --- */ } /** @type Phaser.Group */ var level1_proto = Object.create(Phaser.Group.prototype); level1.prototype = level1_proto; level1.prototype.constructor = Phaser.Group; /* --- end generated code --- */ Player Prefab Player = function (game, x, y) { "use strict"; Phaser.Sprite.call(this, game, x, y, 'characters', 'gunther0'); this.anchor.setTo(0.5, 0.0); this.animations.add('walk', ['gunther0', 'gunther1', 'gunther2', 'gunther3'], 4, true); this.animations.add('jump', ['gunther4', 'gunther5', 'gunther6', 'gunther7'], 4, true); this.animations.add('attack', ['gunther11', 'gunther10', 'gunther11', 'gunther12'], 12, false); this.animations.add('idle', ['gunther0'], 1, true); this.game.physics.arcade.enableBody(this); this.body.setSize(16.818477630615234, 22.794174194335938, 7.9137725830078125, 8.075286865234375); this.body.drag.x = 300; this.body.bounce.set(0.2); this.attack = 0; this.attacking = false; this.attacanim = false; this.touching = false; this.underwater = false; this.invulnerable = false; this.cursors = this.game.input.keyboard.createCursorKeys(); this.game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SHIFT ]); this.game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ]); }; Player.prototype = Object.create(Phaser.Sprite.prototype); Player.prototype.constructor = Player; /** * Automatically called by World.update */ Player.prototype.update = function() { "use strict"; var expend = 0; if (this.game.curEnergy > this.game.maxEnergy) { this.game.curEnergy = this.game.maxEnergy; } else if (this.game.curEnergy < 0) { this.game.curEnergy = 0; } if (this.game.curHealth > this.game.maxHealth) { this.game.curHealth = this.game.maxHealth; } else if (this.game.curHealth < 0) { this.game.curHealth = 0; } if (this.game.curMana > this.game.maxMana) { this.game.curMana = this.game.maxMana; } else if (this.game.curMana < 0) { this.game.curMana = 0; } if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) && this.attacking === false) { this.attacanim = true; this.weapon = new steelSword (this.game, this.x, this.y); this.game.add.existing(this.weapon); this.attack = this.game.add.group(); this.attack.add(this.weapon); if (this.scale.x === -1) { this.weapon.scale.x = -1; } else if (this.scale.x === 1) { this.weapon.scale.x = 1; } this.attacking = true; this.game.time.events.add(Phaser.Timer.SECOND * .08, this.attacktime, this); } else if (!this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) { this.attacking = false; } //CONTROLS //shift key for running and leaping if (this.game.input.keyboard.isDown(Phaser.Keyboard.SHIFT) && (this.game.curEnergy > 0)) { this.game.curEnergy -= .5; //this.scene.EnergyText.setText('Energy: ' + ENERGY); expend = this.game.effort; } else { //ENERGY += .2; //this.scene.EnergyText.setText('Energy: ' + ENERGY); expend = 0; } if (this.game.input.keyboard.isDown(Phaser.Keyboard.SHIFT)) { // Nothing } else { this.game.curEnergy += .2; } if (this.cursors.left.isDown) { // move to the left this.body.velocity.x = -60 - expend; } else if (this.cursors.right.isDown) { // move to the right this.body.velocity.x = 60 + expend; } else { // dont move in the horizontal this.body.velocity.x = 0; } // a flag to know if the player is (down) touching the platforms this.touching = this.body.touching.down; if (this.touching && this.cursors.up.isDown) { // jump if the player is on top of a platform and the up key is pressed this.body.velocity.y = -250 - expend; } if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) && this.attacanim) { this.play("attack"); } else if (this.touching) { if (this.body.velocity.x == 0) { // if it is not moving horizontally play the idle this.play("idle"); } else { // if it is moving play the walk this.play("walk"); } } else { // it is not touching the platforms so it means it is jumping. this.play("jump"); } // update the facing of the player if (this.cursors.left.isDown) { // face left this.scale.x = -1; } else if (this.cursors.right.isDown) { // face right this.scale.x = 1; } }; Player.prototype.hurt = function(attack) { if (this.invulnerable === false){ this.tint = 0xd95763; this.game.curHealth -= attack; this.game.time.events.add(Phaser.Timer.SECOND * .1, this.normalize, this); this.invulnerable = true; } }; Player.prototype.normalize = function(sprite) { this.tint = 0xffffff; this.invulnerable = false; }; Player.prototype.attacktime = function(sprite) { this.attacanim = false; };
  11. Phaser login/signup form

    Hi, I am developing a game in phaser but I am newbie yet. I want to create a login/signup/fb form in the main screen of the game. I did a html form in the index.html of phaser, but I have some doubts. How could I achieve the communication between the html and the scenes of phaser? I created global variables, but I think that is not a good practice. Are there any options to use a state from html like MyGame.MainPage.startGame()? This is the js script of the index, the function is associated to login button: function login(){ user = check_user_in_db(); if(user){ //If the login is correct variable.startGame(); } } This is the MainPage scene of Phaser: /*********************NAMESPACE********************/ var MyGame = MyGame || {}; /**************************************************/ /******************INIT APP SCENE******************/ MyGame.MainPage = function(game) { variable = this; }; MyGame.MainPage.prototype = { init: function() { }, // init preload: function() { //load Sprites }, //preload create: function() { //create Buttons }, // create shutdown: function() { }, // shutdown startGame: function(){ this.state.start("Menu", true, false); } };
  12. Hi guys, I've tried everything, but still cannot get my game to have states. I hate to post my whole code but I have no idea what else to do. If anyone has a bit of time, please let me know what you think. A noob in these matters, I still don't get why I have to use 'this'. Also tried to do this in different files but nothing. I just want a basic 'play' menu, the actual game, and then the 'play again'. Am I doing something wrong in the code that prevents this to have states? I also tried the game.pause = true, but as it pauses everything and buttons won't work. 'use strict'; let game = new Phaser.Game(800, 600, Phaser.CANVAS, 'showgame', { preload: preload, create: create, update: update, render: render, }); function preload () { game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.pageAlignHorizontally = true; game.scale.pageAlignVertically = true; game.stage.backgroundColor = '#000'; game.load.image('ground', './assets/scripts/game/images/ground.jpg'); game.load.image('star', 'assets/scripts/game/images/star.png'); game.load.image('sadmicrowave', 'assets/scripts/game/images/sadmicrowave.png'); game.load.atlasJSONHash( 'sprites', './assets/scripts/game/images/spritesheet-mini.png', './assets/scripts/game/images/spritesheet-mini.json' ); game.load.atlasJSONHash( 'enemies', './assets/scripts/game/images/students.png', './assets/scripts/game/images/students.json' ); } let sadmicrowave; let katie; let students; let tables; let cursors; let score = 0; let scoreText; let timerText; let weapon; let fireButton; let table1; let showgame = document.getElementById('showgame'); let scorediv = document.getElementById('scorediv'); let scorelabel = document.getElementById('label'); function create() { let ground = game.add.image(0, 0, 'ground'); ground.fixedToCamera = true; // Enable p2 physics game.physics.startSystem(Phaser.Physics.P2JS); game.physics.p2.setImpactEvents(true); game.physics.p2.defaultRestitution = 0.8; // Collission Groups let playerCollisionGroup = game.physics.p2.createCollisionGroup(); let studentCollisionGroup = game.physics.p2.createCollisionGroup(); let table1CollisionGroup = game.physics.p2.createCollisionGroup(); game.physics.p2.updateBoundsCollisionGroup(); let x = game.world.randomX; let y = game.world.randomY; //weapon - does not work yet weapon = game.add.weapon(30, 'sprites', 'chair.png'); weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; weapon.bulletSpeed = 500; weapon.fireRate = 600; // main character katie = game.add.sprite (700, 300, 'sprites','katie.png'); game.physics.p2.enable(katie); katie.body.setCircle(30); katie.body.setZeroDamping(); katie.scale.x *= -1; katie.anchor.set(0.5); katie.body.fixedRotation = true; katie.smoothed = false; katie.body.setCollisionGroup(playerCollisionGroup); katie.body.collides(studentCollisionGroup, hitStudent); katie.body.collides(table1CollisionGroup, hitTable); game.camera.follow(katie); weapon.trackSprite(katie, 0, 0, true); fireButton = this.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR); let students = game.add.group(); students.enableBody = true; students.physicsBodyType = Phaser.Physics.P2JS; students.smoothed = false; for (let i = 0; i < 23; i++) { // let student = students.create(190 + 69 * i, -90, 'enemies', i); let student = students.create(x, y, 'enemies', i); student.body.setRectangle(30,30, 0, 0, 4); student.body.setZeroDamping(); student.body.fixedRotation = true; student.body.setCollisionGroup(studentCollisionGroup); student.body.collides([ studentCollisionGroup, playerCollisionGroup, table1CollisionGroup ]); } students.setAll('inputEnabled', true); students.setAll('input.useHandCursor', true); let tables = game.add.physicsGroup(); tables.enableBody = true; tables.physicsBodyType = Phaser.Physics.P2JS; tables.smoothed = false; // for (let i = 0; i < 100; i++) { let table1 = tables.create(x, y, 'sprites', 'table.png'); table1.body.setRectangle(10,10, 0, 0, 0); table1.body.setZeroDamping(); table1.body.setCollisionGroup(table1CollisionGroup); table1.body.collides([ studentCollisionGroup, playerCollisionGroup ]); } let door = game.add.sprite (20, 500, 'sprites', 'door.png'); cursors = game.input.keyboard.createCursorKeys(); scoreText = game.add.text(16, 16, 'Score: 0', { fontSize: '32px', fill: '#000' }); timerText = game.add.text(530, 16, 'Time: ', { fontSize: '32px', fill: '#000' }); game.time.events.add(Phaser.Timer.SECOND * 30, fadePicture); } function hitStudent(katie, student) { // student.health = 2; // for each {student.sprite.alpha -= 0.5}; student.sprite.alpha -= 1; score += 10; student.destroy(); } function hitTable(katie, table1) { // student.health = 2; // for each {student.sprite.alpha -= 0.5}; table1.sprite.alpha -= 0.5; } // GAME OVER function gameover () { game.destroy(); console.log('game destroyed'); } function fadePicture() { game.add.tween(katie).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true); game.add.tween(scoreText).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true); } function update() { katie.body.setZeroVelocity(); if (cursors.left.isDown) { katie.body.moveLeft(350); } else if (cursors.right.isDown) { katie.body.moveRight(350); } if (cursors.up.isDown) { katie.body.moveUp(350); } else if (cursors.down.isDown) { katie.body.moveDown(350); } if (fireButton.isDown) { weapon.fire(); } } function render() { scoreText.text = 'Score: ' + score; timerText.text = 'Time Left: ' + game.time.events.duration; if ( game.time.events.duration === 0 ) { gameover(); } }
  13. Hi all, I'm trying to get a handle on using states correctly. I'm creating a fishing game, which has an over-world you walk around in, and can approach different bodies of water. Once you get near one you can press space to fish. I then start a new state, which will be a mini-game where you try to catch the fish. Then I want to return to the over-world with a successful (or not) catch. Right now, I can start the mini-game phase (miniGame.js), passing in the fish to catch, but when I return to the overworld (Game.js), I can't display the fish or add it to the inventory, because I'm trying to do this in the init function, which requires functions that are defined later in phaser. the player character's position is also reset because create runs right after init. I don't need to run everything in create again right? Because I've already created the map and sprites. Looking at the docs for the phaser state manager, I'm doing: this.state.start('miniGame', false, false, fishOnLine); where the two booleans are for not clearing the world and not clearing the cache, I thought that this would make it easier to return to game state. The fishOnLine contains data about the fish to be caught. After the miniGame I try to return to the Game with the following: this.state.start('Game', false, false, caughtFish, this.fishOnLine); caughtFish is a boolean for if the catch was successful. For now I haven't made the miniGame, and I always return it true. this.fishOnLine is the same fish data as fishOnLine from before. But when the Game state starts, the player's position is reset, and the inventory and display functionality don't work or throw an error. Nothing happens. What am I missing? How can I fluidly transition between two states? Most state examples show you how to add a top score to a title screen, but I need to be able to not reset the game when returning to it. Below is my code for the two game states, the cull code can be seen here Game.js: var TopDownGame = TopDownGame || {}; //title screen TopDownGame.Game = function() {}; TopDownGame.Game.prototype = { init: function(caughtFish, fishOnLine) { if (caughtFish != null || undefined && caughtFish) { var fish = fishOnLine; this.makeFlowersDance(); console.log('caught a ' + fish.name); //show the fish on screen above player this.displayFish(fish); //add a copy of the fish to player's inventory var fishCopy = new this.Fish(fish.name, fish.size, fish.price); this.addFishToInventory(fishCopy); } else if (caughtFish != null || undefined && !caughtFish){ console.log('no fish, sorry man'); } }, create: function() { this.map = this.game.add.tilemap('beach'); //the first parameter is the tileset name as specified in Tiled, the second is the key to the asset this.map.addTilesetImage('basicTiles', 'gameTiles'); //create layers this.backgroundlayer = this.map.createLayer('background'); this.blockedLayer = this.map.createLayer('blockedLayer'); //console.log(this.blockedLayer); //console.log(this.blockedLayer._results); console.log(fishJSON); //create yellow flowers group this.yellowFlowers = this.game.add.group(); for (var i = 0; i < 5; i++) { this.yellowFlowers.create(this.game.rnd.integerInRange(0, 400), this.game.rnd.integerInRange(100, 300), 'yellowFlower', 0); } this.yellowFlowers.callAll('scale.setTo', 'scale', .5, .5); this.yellowFlowers.callAll('animations.add', 'animations', 'dance', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 8, false); //create purple flower sprite this.purpleFlower = this.game.add.sprite(150, 240, 'purpleFlower'); this.purpleFlower.animations.add('dance', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 8, false); this.purpleFlower.scale.setTo(.5, .5) //create fishing group this.fishingZones = []; for (var i = 0; i < this.map.objects.objectsLayer.length; i++) { var zone = this.createFishingTiles(this.map.objects.objectsLayer[i]); this.fishingZones.push(zone); } //collision on blockedLayer this.map.setCollisionBetween(1, 2000, true, 'blockedLayer'); //resizes the game world to match the layer dimensions this.backgroundlayer.resizeWorld(); this.game.physics.startSystem(Phaser.Physics.ARCADE); //Get the Hour this.hour = this.getTime(); //and draw it in the top left corner this.getTimeText(this.hour); //Get Time of Day: Morning, Day or Night this.timeOfDay = this.getTimeOfDay(this.hour); //for testing only this.timeOfDay = "day"; console.log(this.timeOfDay); //create inventory this.inventory = []; //create player this.player = this.game.add.sprite(100, 300, 'player'); this.player.animations.add('right', [0, 1, 2, 3], 10, true); this.player.animations.add('left', [4, 5, 6, 7], 10, true); this.game.physics.arcade.enable(this.player); this.player.body.collideWorldBounds = true; //the camera will follow the player in the world this.game.camera.follow(this.player); //move player with cursor keys this.cursors = this.game.input.keyboard.createCursorKeys(); this.spacebar = this.game.input.keyboard.addKey(32); this.spacebar.onDown.add(this.fishCheck, this); }, createFishingTiles: function(obj) { var fishingTiles = new Phaser.Rectangle(obj.x, obj.y, obj.width, obj.height); fishingTiles.name = obj.name; return fishingTiles; }, update: function() { //collisions this.game.physics.arcade.collide(this.player, this.blockedLayer); //player movement this.player.body.velocity.y = 0; this.player.body.velocity.x = 0; if (this.cursors.up.isDown) { this.player.body.velocity.y -= 50; this.player.facing = "up"; } else if (this.cursors.down.isDown) { this.player.body.velocity.y += 50; this.player.facing = "down"; } if (this.cursors.left.isDown) { this.player.body.velocity.x -= 50; this.player.animations.play('left'); this.player.facing = "left"; } else if (this.cursors.right.isDown) { this.player.body.velocity.x += 50; this.player.animations.play('right'); this.player.facing = "right"; } else { this.player.animations.stop(); } }, fishCheck: function() { for (var x = 0; x < this.fishingZones.length; x++) { //if the center of the player is in range if (this.fishingZones[x].contains(this.player.x + this.player.width / 2, this.player.y + this.player.height / 2)) { console.log('fishing ' + this.fishingZones[x].name); //get the fish to be caught from zone and time of day var fish = this.getFish(this.fishingZones[x].name, this.timeOfDay); //start the mini-game this.chanceToCatch(fish); } } }, getTime: function() { var d = new Date(); var hour = d.getHours(); return hour; }, getTimeText: function(hour) { var meridiem = "am" if (hour > 12) { hour = hour - 12; meridiem = "pm" } hour = hour + meridiem; this.style = { font: "12px Arial", fill: "white", wordWrap: true, wordWrapWidth: 100, align: "center", backgroundColor: "black" }; text = this.game.add.text(0, 0, hour, this.style); text.fixedToCamera = true; }, getTimeOfDay: function(hour) { console.log(hour); if (hour < 5) { return "night"; } else if (hour >= 5 && hour < 11) { return "morning"; } else if (hour >= 11 && hour < 19) { return "day"; } else if (hour >= 19 && hour < 24) { return "night"; } }, makeFlowersDance: function() { this.yellowFlowers.getRandom().animations.play('dance') this.purpleFlower.animations.play('dance'); }, chanceToCatch: function(fishOnLine) { /* var num = this.game.rnd.integerInRange(0, 1); if(num == 0){ return true; } else { return false; } */ this.state.start('miniGame', false, false, fishOnLine); }, getFish: function(zone, timeOfDay) { //zone and timeOfDay are working as a way to get into the object zone = zone.toLowerCase(); console.log(fishJSON.zone[zone].time[timeOfDay]); return fishJSON.zone[zone].time[timeOfDay].fish[1]; }, displayFish: function(fish) { var sprite = fish.name.toString().toLowerCase(); this.fish = this.game.add.sprite(this.player.x + 8, this.player.y - 16, sprite); this.fish.animations.add('wiggle', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 8, true); this.fish.animations.play('wiggle', 8, false, true); }, addFishToInventory: function(fish) { this.inventory.push(fish); console.log(this.inventory); this.updateInventoryDisplay(); }, Fish: function(name, size, value) { this.name = name; this.size = size; this.value = value; }, updateInventoryDisplay: function() { //for every item in the inventory for (var i = 0; i < this.inventory.length; i++) { //get the sprite image from the name in the inventory var sprite = this.inventory[i].name.toString().toLowerCase(); // add the sprite var invFish = this.game.add.sprite(350, 10 * i, sprite); invFish.scale.setTo(.5, .5); invFish.fixedToCamera = true } } } MiniGame.js: TopDownGame.miniGame = function(){}; TopDownGame.miniGame.prototype = { init: function(fishOnLine){ this.fishOnLine = fishOnLine; }, preload: function() { //show loading screen this.preloadBar = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'preloadbar'); this.preloadBar.anchor.setTo(0.5); this.load.setPreloadSprite(this.preloadBar); }, create: function(fishOnLine) { var caughtFish = true; this.state.start('Game', false, false, caughtFish, this.fishOnLine); } };
  14. Hi, for my game I use a simple state order like: Main Menu -> Map screen -> Level 1 -> Map screen -> Level 2 -> and so on That works well Just separate everything in logical chunks. But now I had the Idea of implementing some kind of minigames interrupting the level. And thats the point. If I make a state change, the state is resetted if the minigame itself is a state too. Other version is, that the minigame is just a game packed in a group on top of the current state. but this approach make some trouble too cause of physics side effects. So what I desire: Push a new state, play that state and then pop this state and get the old state right there where it ends before. For me this push/pop approach sound very "correct" and intuitive. Is this possible with phaser somehow? Thanks Tom
  15. Here's my situation: When the main game state starts, it generates a couple hundred objects (sprites, images, etc) scattered around the world, but when I change to a different state, the objects are removed as normal, and when I change states back to the main state, the objects are re-generated. I'm trying to figure out a way to not re-generate that large number of already-generated objects when I switch back to the main state. I already know that game.state.start() gives you the option to not clear the world, but this keeps the objects from the previous state displayed. Is there a way to store those objects so they don't appear when the state changes and then reappear on the screen where they were when the state is set back to the first state? More details: I'm making an AR mobile game that uses random seeds based on the current geolocation and time (rounded to minutes) to generate objects with limited lifetimes. I'm trying to make it so that objects that are close to being destroyed still appear even though re-generating the objects would not generate them. For example, an object was generated 5 minutes ago and will die in 2 minutes. The state changes and the player does stuff in that state then goes back. The object still should have 1 minute left before it disappears but it is already gone because time has moved forward to the point where it would not generate the object again. I'd like that object to remain and live out that last minute of its life since it was there before the player changed states and should be there when they get back.
  16. switch tabs and states problem

    I just finished my Phaser based MMO game and got a big problem. Please help me and sorry for my English. So: 1) I start my game in browser. 2) Then I do switch tabs and minimize the game in browser. 3) Then this command starts: this.game.state.start("game", true, false, ...); 4) And the problem is, that callback function "myState.preload" doesn't start before you switch back to the game.
  17. How would you approach this

    Hi all, This is a bit of a general question... Imagine that you have one game/application of sorts, like this: one main menu with access to 9 different areas; each of those 9 areas has from 1 up to 4 different "games", with up to 4 difficulty levels (each with its own main image, instructions and so on); Any of those games can be started by choosing 1 of 19 possible "keys"; ... I'm passing the keys (that control images and so on) in a .json file and using localStorage to keep the player choices and direct it to the proper place. My big question right now is: should I look at the 9 areas with different levels as being each a state inside a main project or should each be its own little project accessed by the main one? For example, main State (with Boot, Preload, ...) just for showing loader and main menu (plus help and so on) and have something like area01_game01_level01 state; area01_game01_level02 state, area01_game02_level01 state,..., area09_game01_level01; OR main, boot, preload... states and after the player choices are entered, again a main, boot, preload, etc... What's easier to maintain and more logical? Pros and cons... And why? Thanks in advance for all your ideas! Ps - For the record I already have it running in a mix of phaser and plain JS (some games) but each has its own folder and there are BIG folders for html, js, etc...I just want to improve it and make it cleaner!
  18. Hello! I am making a waste sorting game and when the player loses all their lives, I wish to restart the game. I click the 'RETRY' text and the state reloads, but it seems that my life and garbage sprites never reload. I am wondering if it is because they are in an array (see this.garbage = []; and this.lifeSprites = [];). I have never used game.state.start to reload a state multiple times, I have only ever used it to call a state once. If I cannot get game.state.start to reload my game, I will create a restart() method with some re-positioning code and whatnot. BUT it would be way awesome if I could figure out why this doesn't work!! Below is my code and here is a link to my game so far (my code is still mucho messy). Arrow keys to rotate on desktop. BasicGame.Game = function (game) { this.firstDrop = true; this.garbage = []; this.MAX_TRASH = 5; this.lowestTrash = null; this.lastLowestTrash = null; this.lowestTrashType = null; this.lives = 3; this.lifeSprites = []; this.gap = 500; this.MIN_GAP = 250; this.fallSpeed = 3; this.MAX_FALL_SPEED = 5.5; this.sorter = null; this.rotationSpeed = 10; this.targetRotation = null; this.isRotating = false; this.clockwise = true; this.orientation = null; this.Orientation = { NORTH: 0, EAST: -90, SOUTH: -180, WEST: 90 }; this.TrashType = { BLUE: 0, COMPOST: 1, GREY: 2, YELLOW: 3 }; this.leftKey = null; this.rightKey = null; this.gameover = false; this.score = 0; this.scoreText = null; this.highScoreText = null; this.msgText = null; this.continuePrompt = null; }; BasicGame.Game.prototype = { create: function () { this.lowestTrash = 0; this.lastLowestTrash = this.MAX_TRASH - 1; var trash; for (i = 0; i < this.MAX_TRASH; i++) { trash = this.game.add.sprite(this.game.world.centerX, -this.gap * (i + 1), 'trash'); trash.loadTexture('trash', this.rnd.integerInRange(0, this.MAX_TRASH)); trash.anchor.setTo(0.5); this.garbage.push(trash); if (i == 0) { this.lowestTrashType = trash.frame; } } var life; for (i = 0; i < this.lives; i++) { life = this.game.add.sprite(0, 0, 'life'); life.anchor.setTo(0.5); life.x = (this.game.width - (life.width / 2 + 10)) - (i * life.width); life.y = life.height - 10; this.lifeSprites.push(life); } this.sorter = this.game.add.sprite(this.game.world.centerX, this.game.height, 'sorter'); this.sorter.anchor.setTo(0.5); this.orientation = this.Orientation.NORTH; this.targetRotation = this.orientation; this.scoreText = this.add.bitmapText(25, 25, 'arialPixelated', '0', 16); this.scoreText.align = 'left'; this.highScoreText = this.add.bitmapText(25, 50, 'arialPixelated', 'BEST: ' + BasicGame.highScore, 16); this.highScoreText.align = 'left'; this.continuePrompt = new SuperBitmapText(this.game, this.game.world.centerX, this.game.world.centerY + 100, 'arialPixelated', 'RETRY', 16, 25); this.continuePrompt.anchor.setTo(0.5); this.continuePrompt.align = 'left'; this.continuePrompt.alpha = 0; this.continuePrompt.inputEnabled = false; this.msgText = this.add.bitmapText(this.game.world.centerX, this.game.world.centerY, 'arialPixelated', '', 16); this.msgText.anchor.setTo(0.5); this.msgText.align = 'center'; this.game.input.onDown.add(this.rotateSorter, this); this.game.input.onDown.add(function() {if (this.continuePrompt.isDown){this.game.state.start('Game', true, false);}}, this); this.leftKey = this.game.input.keyboard.addKey(Phaser.Keyboard.LEFT); this.rightKey = this.game.input.keyboard.addKey(Phaser.Keyboard.RIGHT); this.game.input.keyboard.addCallbacks(this, this.rotateSorter); //For mobile. Phaser.Canvas.setTouchAction(this.game.canvas, 'auto'); this.game.input.touch.preventDefault = true; }, update : function () { if (!this.gameover) { this.garbage.forEach(function(trash) { trash.y += this.fallSpeed; trash.angle += 0.25; }, this); if (this.garbage[this.lowestTrash].y > this.game.height - (this.sorter.height / 2.5)) { this.checkIfScored(); } } this.sorter.angle = Phaser.Math.snapTo(this.sorter.angle, this.rotationSpeed); if (this.sorter.angle != this.targetRotation) { this.isRotating = true; } else { this.isRotating = false; } if (this.isRotating) { if (this.clockwise) { this.sorter.angle += this.rotationSpeed; } else { this.sorter.angle -= this.rotationSpeed; } } }, resetTrash : function () { this.garbage[this.lowestTrash].y += -this.gap * (this.MAX_TRASH); this.garbage[this.lowestTrash].loadTexture('trash', this.rnd.integerInRange(0, this.MAX_TRASH)); this.lowestTrash++; if (this.lowestTrash > this.garbage.length - 1) { this.lowestTrash = 0; } this.lowestTrashType = this.garbage[this.lowestTrash].frame; }, checkIfScored : function () { if (this.lowestTrashType == this.TrashType.BLUE && this.orientation == this.Orientation.NORTH) { this.score++; if (this.gap > this.MIN_GAP) { this.gap -= 5; } else { this.gap = this.MIN_GAP; } if (this.fallSpeed < this.MAX_FALL_SPEED) { this.fallSpeed += 0.05; } else { this.fallSpeed = this.MAX_FALL_SPEED; } } else if (this.lowestTrashType == this.TrashType.COMPOST && this.orientation == this.Orientation.EAST) { this.score++; if (this.gap > this.MIN_GAP) { this.gap -= 5; } else { this.gap = this.MIN_GAP; } if (this.fallSpeed < this.MAX_FALL_SPEED) { this.fallSpeed += 0.05; } else { this.fallSpeed = this.MAX_FALL_SPEED; } } else if (this.lowestTrashType == this.TrashType.GREY && this.orientation == this.Orientation.SOUTH) { this.score++; if (this.gap > this.MIN_GAP) { this.gap -= 5; } else { this.gap = this.MIN_GAP; } if (this.fallSpeed < this.MAX_FALL_SPEED) { this.fallSpeed += 0.05; } else { this.fallSpeed = this.MAX_FALL_SPEED; } } else if (this.lowestTrashType == this.TrashType.YELLOW && this.orientation == this.Orientation.WEST) { this.score++; if (this.gap > this.MIN_GAP) { this.gap -= 5; } else { this.gap = this.MIN_GAP; } if (this.fallSpeed < this.MAX_FALL_SPEED) { this.fallSpeed += 0.05; } else { this.fallSpeed = this.MAX_FALL_SPEED; } } else { this.fallSpeed = 3; this.updateLives(); } this.resetTrash(); this.scoreText.setText(this.score); }, updateLives : function () { this.lifeSprites[this.lives - 1].loadTexture('lifeFull'); this.lives--; if (this.lives == 0) { this.gameover = true; this.msgText.setText('GAME OVER!\n' + this.score + ' responsibly disposed trashes!'); this.continuePrompt.alpha = 1; this.continuePrompt.inputEnabled = true; this.continuePrompt.input.useHandCursor = true; if (this.score > BasicGame.highScore) { BasicGame.highScore = this.score; this.highScoreText.setText('BEST: ' + BasicGame.highScore); } this.garbage.forEach(function(trash) { trash.kill(); }, this); this.game.input.onDown.remove(this.rotateSorter, this); } }, rotateSorter : function () { if (this.game.device.desktop && !this.gameover) { if (this.leftKey.isDown) { this.rotateLeft(); } else if (this.rightKey.isDown) { this.rotateRight(); } } else { if (this.input.y >= this.sorter.y - this.sorter.height) { if (this.input.x >= this.game.world.centerX) { this.rotateRight(); } else if (this.input.x < this.game.world.centerX) { this.rotateLeft(); } } } }, rotateLeft : function () { this.clockwise = true; switch (this.orientation) { case this.Orientation.NORTH: this.orientation = this.Orientation.WEST; break; case this.Orientation.EAST: this.orientation = this.Orientation.NORTH; break; case this.Orientation.SOUTH: this.orientation = this.Orientation.EAST; break; case this.Orientation.WEST: this.orientation = this.Orientation.SOUTH; break; } this.targetRotation = this.orientation; }, rotateRight : function () { this.clockwise = false; switch (this.orientation) { case this.Orientation.NORTH: this.orientation = this.Orientation.EAST; break; case this.Orientation.EAST: this.orientation = this.Orientation.SOUTH; break; case this.Orientation.SOUTH: this.orientation = this.Orientation.WEST; break; case this.Orientation.WEST: this.orientation = this.Orientation.NORTH; break; } this.targetRotation = this.orientation; } }; EDIT: My input listeners also get jacked up. I separate mobile and desktop but when the state restarts, my mobile listeners are firing when they shouldn't be because I am using desktop, not mobile.
  19. Hey everyone, I am currently coding a boilerplate for scientist like myself who wish to create web based tasks using the latest technology the web has to offer This boilerplate is not aimed to be babylon.js specific but the two main example from which users could build upon would be in 3d in BabylonJS and in 2D probably using ... phaser ? did not decide yet. The design needs to be built independently of the game engine used and I was wondering if you had any advices on how i should build my object hierarchy. What is special with experimental tasks is that everything has to be collected at the millisecond, well stored, exportable etc. So beside the general hassle of building a robust game state system I need to handle inputs and data asynchronously. I created this little flow chart that you are welcome to modify if you have any relevant comment/idea, I'll be very glad to have any input from you guys ! https://drive.google.com/file/d/0BxggOFF8_iXkLUpXeXlyTkh2a2c/view?usp=sharing Thank you !
  20. Ways to implement Zelda-like rooms

    Hey everyone. Lately I've been screwing around with a Zelda-like room system and I wanted to see how others would tackle it using Phaser. Right now I just have a Tiled tilemap that has 2 layers, one for the background and one for collisions, and a player sprite. On update() I check the players position and set the cameras target position to match the bounds of the "room" the player is in and the camera slides over into place, very similar to the 2d Zelda games like the originial Zelda NES, Links Awakening, Oracle of Seasons/Ages, etc. It works extremely well, even with a huge tilemap with background, collision and object layers. The only problem is that the tilemap is really just one large room and the view into the room just snaps to certain places as the player walks around. Basically it's an illusion of rooms using the camera. All entities in the world exist and are updated even if they are in a different "room" or even on the opposite side of the map. I've researched a bit and so far I feel I have a few ways: 1) Deactivate all entities that are off screen. Basically just stop rendering them and remove the physics body, AI, etc. There is a way to do this in Phaser api though I can't remember the function call right now. This way all entities are still existing in the game world, but are just not taking up cycles rendering or updating them. A con of this I think would be that with a lot of entities in the world just turning off it's render and update doesn't free up memory because the entities are never actually destroyed. 2) Basically when loading the tilemap create a separate pool of entities for each type of object on the map, but deactivate all of them. Keep a current_room property on all entities. When the player transitions to a new screen it's current_room prop is updated and then check all entities to see if it's current_room prop is the same as the players current_room, meaning they are in the same room, and if so deactivate all entities and activate the entities that are in the same room as the player. 3) On the tilemap set enemy spawn points in certain locations. There is a sprite pool for enemies_on_screen and when a player moves into a new room the enemies_on_screen are deactivated and we check through all spawner tiles on screen and spawn an enemy on that tile and push it into the enemies_on_screen. This way would be most similar to Zelda NES. The player enters a room and enemies spawn in a random location. There are of course other ways I'm sure. I guess what I'm trying to figure out is how to structure the game world/rooms/etc. I don't like how "open" the game world is and how little structure my current system puts on rooms. But I like being able to design the whole overworld map at once in Tiled. I think if I would have to design each room separately and then fit them into place during runtime would drive me crazy. xD Any advice would be greatly appreciated! And I'm sorry if my thoughts seem jumbled, I've been up for too many hours and caffeine levels are dangerously low...
  21. State Management

    Hello fellow Game-Devs! I am building a local multiplayer bomberman prototype to learn Phaser. I've split up the game code into different states. When I switch from one state to another the content of the previous state is still rendered. If you want to trigger the state change manually (in case you dont have a 360 controller) just open the browser console and type: bomberman.engine.state.start('Menu'); The complete source code is available here: https://github.com/Luketep/bomberman/tree/bomberman-local-multiplayer How to run the game locally: # Checkout the repo and correct branch git clone https://github.com/Luketep/bomberman.git && cd bomberman git checkout bomberman-local-multiplayer # install deps npm install -g gulp npm install # run express server node app.js # in a separate cli window, run file watcher gulp watch Game.js create function // setup states game.state.add('SplashScreen', new SplashScreen()); game.state.add('Menu', new Menu()); game.state.add('Credits', new Credits()); game.state.add('Level', new Level()); game.state.add('Score', new Score()); game.state.add('PlayerSelect', new PlayerSelect()); // run initial state game.state.start('SplashScreen'); Console output // Game is loading SplashScreen: preload SplashScreen: create SplashScreen: startPreload SplashScreen: loadStart SplashScreen: fileComplete xbox360 SplashScreen: loadComplete // Manual state change trigger bomberman.engine.state.start('Menu'); // Splashscreen is cleaning up Destroying 3 entities for SplashScreen // Menu State is loaded Menu: preload Menu: create Menu: startPreload // somehow SplashScreen also starts loading SplashScreen: loadStart Menu: loadStart SplashScreen: fileComplete xbox360 Menu: fileComplete xbox360 SplashScreen: loadComplete Menu: loadComplete
  22. Cant load state

    Hello, I'm trying to move my existing project to Intel XDK. I've succesfully moved my preload state that is working, but I can't start next state. Please take a look at my code, probably it is some scope problem (usually i have problems with that ) So in index.html I load the scripts : <script src="lib/phaser.min.js"></script> <!-- Load game source files --> <script src="src/Game.js"></script> <script src = "src/preload.js"></script> <script src = "src/intro.js"></script> <!-- Load game entrance --> <script src="src/app.js"></script> Then app.js is executed, where states are loaded (function () { /* globals Phaser:false, BasicGame: false */ // Create your Phaser game and inject it into the game div. // We did it in a window.onload event, but you can do it anywhere (requireJS load, anonymous function, jQuery dom ready, - whatever floats your boat) var game = new Phaser.Game(480, 640); game.state.add('Game', BasicGame.Game); game.state.add('Preload', BasicGame.preload); game.state.add('Intro', BasicGame.intro); game.state.start('Preload'); })(); My preload.js : var BasicGame = { jsonData2 : null, }; BasicGame.preload = function (game) { }; BasicGame.preload.prototype = { init: function () { this.stage.backgroundColor = 0xffffff this.text = this.add.text(this.world.centerX, this.world.centerY, 'LOADING', {font: "30px Arial", fill: "#000000", align: "left"}); }, preload: function () { this.load.json('jsonData', 'asset/smth.json', false); this.load.image('background', 'asset/background.jpg'); }, create: function () { this.jsonData = this.cache.getJSON('jsonData'); jsonData2 = this.jsonData; this.state.start('Intro', false, true, 'W1'); }, }; And here is the place where I get an error : "Phaser.StateManager - No state found with the key: Intro" on line this.state.start(); When I print this in console i get BasicGame.preload. Using BasicGame instead of preload doesn't work as well. EDIT: i'll show you my Intro state : BasicGame.intro = function(game) { this.userPath = []; this.conditionArray = []; this.nodeID = 'W1'; this.node = null; }; BasicGame.intro.prototype = { init: function(nodeID) { this.nodeID = nodeID; this.node = this.getNodeByID(this.nodeID); }, create: function() { this.background = this.add.sprite(0, 0, 'background'); this.background.scale.setTo(2.5); this.displayData(); game.scale.pageAlignHorizontally = true; game.scale.pageAlignVertically = true; // using RESIZE scale mode game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.setScreenSize(true); }, // some not important functions };
  23. Timer at beginning of state

    Hello everyone, I am trying to create a timer that will count down three minutes after the state was started. I am not sure how to make a text that will visualize the timer.(00:00) Can you guys help out?
  24. reusing states multiple times, init once

    HI, When moving back and fourth between say a menu state and a gameplay state, is there a way to not rebuild an entire game or menu each time? init and create seem to get hit every time a state is started. I didn't see much in interphase about proper multiple use of a state, and in the game examples it seems states are always rebuilt each time you move between them. Is that technique better for GC than initilizing game elements just once and reusing? Thanks Ian S
  25. Hello, in my game I will be very often switching states - for example Intro and Office. In each state user can kill some objects, which were created in init function when the state was started for the first time. Lets assume that in the Office state user killed two objects, then he goes to Intro state and then back to Office - is there some way to preserve that state as it was before the state change? Without holding some global array with informations about all objects if they were killed or not? My sample code: intro.js MyGame.intro = function (game) { this.background; this.character;};MyGame.intro.prototype = { create: function () { this.background = this.add.sprite(0, 0, 'loadingBackground'); this.character = game.add.sprite(game.world.centerX, game.world.centerY, 'aml_1', 'aml_avatar_hindus.jpg'); var left = game.add.sprite(game.world.centerX-232, game.world.centerY - 200, 'aml_1', 'strzalka_lewo.png'); var right = game.add.sprite(game.world.centerX+200, game.world.centerY - 200, 'aml_1', 'strzalka_prawo.png'); this.character.anchor.setTo(0.5,0.5); var startBtn = game.add.sprite(game.world.centerX, game.world.centerY+300, 'aml_1', 'letsstart.png'); startBtn.anchor.set(0.5); startBtn.inputEnabled = true; startBtn.events.onInputDown.add(this.startClicked, this); game.scale.pageAlignHorizontally = true; game.scale.pageAlignVertically = true; // using RESIZE scale mode game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.setScreenSize(true); }, startClicked: function () { this.state.start('Office', false, false); } };office.js MyGame.office = function (game) { this.background; this.character; this.sheet; this.btn; this.zszywacz;};MyGame.office.prototype = { init: function () { this.background = this.add.sprite(0, 0, 'officeBackground'); this.sheet = this.add.sprite(game.world.centerX, game.world.centerY, 'aml_1', 'pole.png'); this.sheet.anchor.set(0.5); this.btn = this.add.sprite(game.world.centerX, game.world.centerY + 300, 'aml_1', 'play.png'); this.btn.anchor.set(0.5); this.btn.inputEnabled = true; this.btn.events.onInputDown.add(this.btnClicked, this); this.spawnHiddenObjects(); }, create: function() { }, btnClicked: function() { this.sheet.kill(); this.btn.kill(); console.log(this.sheet); }, spawnHiddenObjects: function() { this.zszywacz = this.add.sprite(1302, 587, 'aml_1', 'zszywacz.png'); this.zszywacz.inputEnabled = true; this.zszywacz.events.onInputDown.add(this.zszywaczClicked, this); }, zszywaczClicked: function() { this.state.start('Intro', false, false); } };Any help would be appreciated, thanks.