Jump to content

Search the Community

Showing results for tags 'states'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • HTML5 Game Coding
    • News
    • Game Showcase
    • Facebook Instant Games
    • Web Gaming Standards
    • Coding and Game Design
    • Paid Promotion (Buy Banner)
  • Frameworks
    • Pixi.js
    • Phaser 3
    • Phaser 2
    • Babylon.js
    • Panda 2
    • melonJS
    • Haxe JS
    • Kiwi.js
  • General
    • General Talk
    • GameMonetize
  • Business
    • Collaborations (un-paid)
    • Jobs (Hiring and Freelance)
    • Services Offered
    • Marketplace (Sell Apps, Websites, Games)

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Twitter


Skype


Location


Interests

  1. this seems a rudimentary task, but i'm actually having trouble implementing a title screen into a game. i've saved this task for last thinking it simple, but i can't seem to find a way to do it cleanly. i believe the creation of "states" is involved, but i can't figure these out, and the one example on the phaser website is hopelessly confusing. everything in this project thus far is located in a single "game.js" file. i tried making a separate "title.js" and going from there, but perhaps this is the wrong approach. i simply want something that occurs before the game.js, shows a static image, and when anything is pressed (either keyboard or mouse) it launches "game.js". any example of this would be great.
  2. Hello, I have different states like "menuState", "optionState", "playState". In optionState I have more than 50 toggle buttons (possible frames: 0 and 1) So, I can include/exclude different cities by clicking those toggle buttons. Let's say I click toggle button next to "Berlin", this city is excluded from an array, and button's frame is set to 1 now. It works fine for all cities, but if I go to menuState or playState, then I go back to optionsState, those toggle buttons are created again, and their frame is 0 by default. Is is possible to save those buttons (keep them on frame 1) after switching the state? I can add different variables to game.js for example, and when toggle button is clicked, set corresponding variable to 0/1. But this requires a lot of coding. Is there any better solution? Thanks
  3. Hi all! Does anyone know where I might look to find some tutorials regarding best practices (basic phaser 3 game code/file structures) and perhaps some resources on STATES? If I could get some resources for using states in Phaser 3 I would really appreciate it! I keep running into an issue with "game.state.add" being undefined? Basically, if someone could point me to some very basic JS related Phaser 3 tutorials (video or article is fine) I would greatly appreciate it! P.S. A little background on me: Several years of experience using PHP/MySQL, released several text based RPG's, designed an open source CMS and assisted a startup for a little while. I have very little experience/knowledge with Javascript/ECMAScript
  4. Hi, I don't know if this is a stupid question, but I want my game to go fullscreen when on mobile/touch screen devices only. I also need it to stay fullscreen across multiple states. Any ideas?
  5. Gammerr

    Phaser States

    So states are the right way of creating screens in the game, right? So let's say I have a menu state and I have a game state, so my game state looks like that: var gameState = { init: function(levelData) { this.levelData = levelData++; }, create: function() { var jumpLebel = game.add.text(140, 200, 'press ESC to jump to MENU', { font: '25px Arial', fill: '#ffffff'}); var escKey = game.input.keyboard.addKey(Phaser.Keyboard.ESC); escKey.onDown.addOnce(this.goToMenu, this); }, start: function() { this.game.state.start('menu', true, false, levelData); } }; Where is the right place to put my init variables of the game on the init function? after the init function? on the create function? should be in another state file? maybe the bootState? Can you help me with that structure please? Also I'm watching the tutorials of Pablo at udemy.com and he's not explaining why sometimes he's using 'this' and sometimes not, for example (section #4, Lecture #39 - Basic Structure): create: function() { this.ground = this.add.sprite(0, 500, 'ground'); var platform = this.add.sprite(0, 300, 'platform'); this.player = this.add.sprite(100, 200, 'player', 3); }
  6. I've read through just about all of this guide (https://github.com/kittykatattack/learningPixi). I think I have a grasp of how to switch stages/scenes. There's one part that doesn't make sense to me however. If I wanted to create a separate .js file for every class and every scene's code, what's the best practice for loading those files? I've seen examples where the index.html file just includes all of the scripts, but isn't that possibly a slow and/or bad experience? A previous flow I read about was loading the bare minimum (a background, logo, and loading graphic) and then loading all other images and javascript files. Is there a best practice to load these separate javascript files through the Pixi loader so the splash screen comes up instantly and show a loading bar while I pull in all these extra assets?
  7. I have been trying to use phaser examples in my games. I noticed that the examples are not using states. The game that I am developing is using states, so I can't use the examples because I keep getting errors. Here's an example of what I am talking about: Phaser example: game.input.onDown.addOnce(updateText, this); my code game.input.onDown.addOnce(this.updateText(), this); What am I doing wrong? What can I do different?
  8. casey

    get state

    I'm trying to get the name of the current state that I am in. getCurrentState() returns a whole lot of information, including but not limited to the specific state name. How do I just return the current state (i.e. 'myCurrentState')? var myCurrentState = { preload: function () { }, create: function () { game.stage.backgroundColor = '#cce5ff'; var test = game.state.getCurrentState(); console.log(test); //logs out way too much info } };
  9. Hello! I wasn't sure what to call it but I am working on a game with my husband (terrible idea, he's a designer..) and he asked if I could create a menu screen that plays out a little scene or something. He showed me this video as an example of Mario Kart SNES (only watch the first 35 seconds of so): https://www.youtube.com/watch?v=AlAmXXNz5ac I am aware of how to use states and all but, I only just started using Phaser and I was trying to think out how I would create something similar to the scene played out in the example (Maybe something not so complex), also if this is possible how would I loop this scene, since a user might leave the scene playing to see the end of it? Thank you in advance for all of your help!!
  10. If I have multiple states (say, 30) that are somewhat resource heavy (audio, background graphic, graphics), is it better to run a single preloader at the start and preload everything I'm going to need in the game, or preload the next state ahead in each state? So if I'm in a room, and can travel to 3 other rooms from my current room, should I be preloading those 3 rooms in my current state while the player is there, etc. or preloading them all in advance?
  11. 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?
  12. 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?
  13. 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(); } }
  14. I recently finished a very simple game, but there's still some juddering and uneven framerate even though there's really not much going on. 2-3 milliseconds per frame according to https://github.com/englercj/phaser-debug All I can think is that there's something that occasionally takes a few too many milliseconds that I need to optimise or move from one state to another. Or maybe there's a deeper problem? What are the best practices for the types of code and game logic recommended for each state? What are the best approaches to finding the offending code and the subsequent optimisation? boot: config preload: asset loading create: object creation update: position changes player logic prerender: ? render: render effects postrender: ?
  15. 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
  16. 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)
  17. 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 !
  18. 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
  19. 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
  20. 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
  21. 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!
  22. 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); } };
  23. 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; };
  24. 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); } };
  25. 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
×
×
  • Create New...