Jump to content

Search the Community

Showing results for tags 'State'.

  • 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. Hi All, I am new to phaser and going through it and i came across state in phaser. I need to know if i can maintain my pervious state active in the background so that i can be able to handle assets loading in the active without getting caught in the Phaser.cache.getImage error. Thanks in advance,
  2. Hi, I've encountered a strage problem while building a little, mostly static mobile game using Intels XDK, Cordova and Phaser (2.4.6). It's targeted at Android and uses the Crosswalk web runtime. I basically followed Matt McFarlands menu tutorial, and created States to do stuff like booting up, loading all assets, showing a splash screen, showing a menu, the levels etc. I'm using one Phaser.Graphics object per State to draw on (my game only needs a few geometric items). Additionaly I'm using the SaveCPU plugin to avoid unnecessary render cycles. Unfortunately removing it doesn't seem to remove the flashing problem. The stage.background is set to white, in the HTML part backgroud colors are also set to white. When moving from one State to the next I nevertheless get strange black flashes after entering the new State. Sometimes they cover the whole viewable area, sometimes they seem to be a black rectangle originating at the canvas center and covering only the lower right quadrant. I only get those flashes on mobile devices, they don't happen in a browser on a PC. I also observed that they seem to appear only after I add the Graphics object to a State, States whithout Graphics objects don't flash. Unfortunately I wasn't able to find out when exactly a flash occurs, but it seems to be either in or before/after init(), preload() or create(). The typical structure of my States looks like that: MyState = function () {} MyState.prototype = { init: function () { game.stage.backgroundColor = "#FFFFFF"; this.graphics = game.make.graphics(0, 0); // do some more stuff, initialise variables etc. }, preload: function () { this.graphics.alpha = 0; this.graphics.width = game.global.canvasWidth; this.graphics.height = game.global.canvasHeight; // do some more stuff }, create: function() { // do some more stuff game.add.existing(this.graphics); // do some more stuff, set up input handlers etc. // graphics fade in game.add.tween(this.graphics).to({alpha: 1}, 1000, Phaser.Easing.Quadratic.Out, true); // rendering was set to 60 FPS in the previous state (probably unnecessarily), // as long as there are active tweens forceRender() of the SaveCPU plugin is called in update() game.global.saveCpu.renderOnFPS = 0; }, update: function () { if (game.global.saveCpu.renderOnFPS === 0 && game.tweens.getAll().length > 0) game.global.saveCpu.forceRender(); }, render: function () { this.graphics.clear(); // draw stuff like menu buttons game pices etc using graphics drawing methods }, // [ ... more methods for state specific stuff ... ] moveToNextState: function (stateName) { // fade out the graphics and move on to the next state game.global.saveCpu.renderOnFPS = 60; var theEndTween = game.add.tween(this.graphics).to({alpha: 0}, 1000, Phaser.Easing.Quadratic.Out, true); theEndTween.onComplete.add(function () { game.state.start(stateName, true, false); }, this); } } So I wonder if anybody has an idea about what causes the flashes and how I may avoid them?
  3. How to pass the cursor object to a method that belongs to a class that inherits the Phaser.Sprite class? I have a class that inherits from Phaser.State in which I create a cursor object and pass it to the update method from another class. class Play extends Phaser.State { create() { this.physics.startSystem(Phaser.Physics.ARCADE) ... this.player = new Player({ game: this.game, x: 32, y: this.world.height - 150, asset: 'dude' }) this.game.add.existing(this.player) } update() { const cursors = this.input.keyboard.createCursorKeys() this.player.update(cursors) } } Player class - problem occurs in the if condition: class Player extends Phaser.Sprite { constructor({ game, x, y, asset }) { super(game, x, y, asset) this.game.physics.arcade.enable(this) this.body.bounce.y = 0.2 this.body.gravity.y = 300 this.body.collideWorldBounds = true this.animations.add('left', [0, 1, 2, 3], 10, true) this.animations.add('right', [5, 6, 7, 8], 10, true) } update(cursors) { this.body.velocity.x = 0 if (cursors.left.isDown) { this.body.velocity.x = -150 this.animations.play('left') } } } Error message: "TypeError t is undefined"
  4. Thanks for you help. I am just a new learner of Phaser. and I use phaser-ce in my project. I add a sprite to a state, and I want to console something after the sprite is clicked down. what I use is "sprite.events.onInputDown.add(function(){console.log('something')},this)", but onInputDown seems to be no work. here is my code: import Phaser from 'phaser' export default class extends Phaser.State { constructor () { super() this.score = 0 this.highestScore = 0 } init () { } preload () { } create () { this.graphic = new Phaser.Graphics(this.game, 0, 0) this.graphic.beginFill(0xffee00) this.graphic.drawRoundedRect(0, 0, 200, 75, 5) this.graphic.endFill() this.textTexture = this.graphic.generateTexture() this.textSprite = this.add.sprite(this.game.width / 2, this.game.height / 2 + 100, this.textTexture) this.textSprite.anchor.setTo(0.5) this.text = new Phaser.Text(game, 0, 0, 'Try Again', { font: '40px', fill: '#ee5000', align: 'center' }) this.text.anchor.setTo(0.5) this.textSprite.addChild(this.text3) this.textSprite.inputEnabled = true //I want to click this sprite, but it seems didn't work, try button still cannot work this.textSprite.events.onInputDown.add(function () { console.log('tap dispatched') }, this) } update () { } render () { game.debug.spriteInfo(this.textSprite, 32, 32) game.debug.spriteInputInfo(this.textSprite, 32, 130) } } Here is some of my code, I want to change the state after getting the click signal. And I find the state.input is Ok. I had googled a long time, can't find the reason. Thanks for your help again.
  5. Hello, how can i start multiple states at the same time together? I want to use something like that _.each(components, (component, index) => { this.promises.push(new Promise((resolve) => { // in component class, i add some state new COMPONENTS[component.name](this.game, resolve, component.props); })); }); Promise.all(this.promises).then((results) => { console.log('Components ' + _.size(results) + ' has been loaded'); _.each(results, (componentName, index) => { this.game.state.start(componentName); }); this.destroy(); }); I like that structure more, is it possible ? i know that update method'll start in the both states and may be it's bad, but i want to make game with this structure. And also if it is possible, how can i stop update method in some states? if you want to see my component it is here: COMPONENTS.Move = class { constructor(game, resolve, props) { this.game = game; this.props = props; this.resolve = resolve; this.canMove = true; this.componentName = 'Move'; this.game.state.add(this.componentName, this); this.resolve(this.componentName); } preload() { // this.game.load.image('tiles', this.props.image); } create() { // this.resolve(this.componentName); } update() { let cursors = this.game.input.keyboard.createCursorKeys(); if (cursors.up.isDown) { this.game.camera.y -= 40; } else if (cursors.down.isDown) { this.game.camera.y += 40; } if (cursors.left.isDown) { this.game.camera.x -= 40; } else if (cursors.right.isDown) { this.game.camera.x += 40; } } }; And may be my english is bad, sorry, im from Russia
  6. Hello, I'm trying to make a game with different states : The first one is the main state (Play.js) where the game is running and I have a second state (Skills.js) to create a Skills Tree. To keep track of my variables I store the data into two JSON file and I pass them when I'm changing state like that : Play => Skills this.game.state.start('Skills', true, false, JSON.stringify(this.gameObject), JSON.stringify(this.skillsObject)); Skills => Play this.game.state.start('Play', true, false, JSON.stringify(this.gameObject), JSON.stringify(this.skillsObject)); However, I have a timer which displays the remaining time and a menu bar in Play.js and I would like to keep displaying them in Skills.js. I made some research and I could turn the "clearWorld" parameter to false but this will keep displaying the others spritesheets and I won't want that. So, how could I do that ?
  7. Does anyone know how to unload and destroy audio files appropriately? I have about 12 MB of audio in my game, or about 15 minutes. I do not load all of them at one time, since this will break any mobile browser. So I load them in the states they are needed. About 4 MB is loaded at the same time. According to the Task Manager in chrome, the memory used by my game just keeps growing and growing, easily above 1000MB by changing states. (Browsers decode audio to lossless => memory use is high, regardless of file format and encoding.) In all states I have a shutdown function that destroys all the sounds and purges audio loaded in the cache. This is my current code (very similar to how cache is cleared when changing states, but I have some assets I use everywhere and don't want to remove): function clearCache () { // Purge sound. var key = this.sound._sounds.length; while (key--) { this.sound._sounds[key].destroy(true); } // Destroy "everything" in cache. for (var i = 0; i < this.cache._cacheMap.length; i++) { var cache = this.cache._cacheMap[i]; for (key in cache) { if (key !== '__default' && key !== '__missing' && this.cache._doNotDelete.indexOf(key) < 0) { if (cache[key].destroy) { cache[key].destroy(); } delete cache[key]; } } }}(Note: This problem did not occur in previous Phaser versions, so I am suspecting that some reference to the audio files are lingering, but can't find out where.) Also, if anyone has a good way of profiling and debugging browser audio, please share, I haven't found a good way to figure out where all this memory goes (Chrome heap profiler says that I use | 20MB).
  8. Hi guys – just discovered Phaser yesterday. Just wondering if anyone has an example of a pause screen/state in a game created? Would be great to see some code. Had a look at the examples in the docs and couldn't see anything. Also, is the only way to pause/resume a game to individually pause and then resume all the moving / relevant elements, or am I missing some amazing game.pause() function? I pretty familiar with JS, but am pretty much a noob at creating games with frameworks. Many thanks, Shaun
  9. I have a global object called "params" that stores a lot of important parameters for my game. I define params in a "main.js" file that initializes the game, defines my states and parameters, and then calls my "bootState". For some reason, when I restart my "gameState" (another state, defined in "gameState.js") it resets my "params" object to the values it was initialized with in "main.js". My goal is to change some parameters via "params" in the console, then restart "gameState" and have it reflect those changed parameters. If needed I can provide some example code.
  10. I had a state serving as a level in my game. In the middle of one of the functions, it would check in an if statement to see if the criterion for beating the stage had been met and would call a function to change state back to main menu. If I then went from the main menu back to the stage after doing that state change, it'd be a buggy mess. I noticed that the "Quit" button that called a barebones function returning to the main menu didn't give me the same problem. What I tried is that after I did the "win" conditional check, I put the rest of the function in an else statement. And it worked! But I don't understand why and I'm concerned for the future. I thought the problem may have been global variables but I'm almost positive that that isn't true here. The way I understood changing states is that any code beneath it was irrelevant. Am I wrong in that assumption? spawnRoom: function(){ this.screen += 1; if(this.screen == 9){ this.completeGame(); } else{ .... } } completeGame: function(){ this.game.sound.stopAll(); this.state.start('Menu'); }
  11. hi, I've been using phaser for some time now but am having some issue with my game when I press the restart button. My game goes into an infinite loop and my player can't jump as high as he used to before. Its like as if gravity increased on the stage. and other objects disappear too like they go all the way down to the screen Can somebody tell me whats wrong here retry: function () { //this.clearCurrentState() this.levelSong.pause() this.winSong.pause() this.gameOverSong.pause() this.shutdown() this.game.state.start('Level2') }, shutdown:function() { this.game.world.removeAll() }, here is the link to my game (My problem is in level 2): https://exit-exitar.firebaseapp.com
  12. 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
  13. Noob here, Having a hard time with making game states to work - I've been following tutorials and still no luck. I'm really looking for an overview of what I have so far on states, more so than an error fix (witch is loadState is not defined in index.html line 23) HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>game v1</title> <script src="phaser.js"></script> <script src="jquery-3.2.1.js"></script> <script src="loadState.js"></script> <script src="update.js"></script> <link rel="stylesheet" href="css/game.css"> </head> <body> <div class="gameDiv"></div> </body> <script type="text/javascript"> (function() { var width = window.innerWidth; var height = window.innerHeight; var game = new Phaser.Game(width, height, Phaser.AUTO, 'gameDiv'); game.state.add("loadState",loadState); game.state.add("updateState",updateState); game.state.start("loadState"); })(); </script> </html> loadState.js: var loadState = { preload: function() { game.load.spritesheet("background" , "assets/backgroundgif2.png", 800, 336); game.load.image("ground","assets/red.png"); game.load.spritesheet("blue_player", "assets/player_sprites/playertwo standing.png", 96, 96); }, create: function(){ game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT; game.physics.startSystem(Phaser.Physics.ARCADE); platforms = game.add.group(); platforms = game.add.physicsGroup(); var background = game.add.sprite(0, 0, 'background'); background.animations.add("background", [0,1,2,3,4,5,6,7,8], 10, true); background.animations.play("background"); background.width = game.width; background.height = game.height; game.world.sendToBack(background); //used this to place background behind platforms var ground = platforms.create(0, game.world.height - 64, 'ground'); platforms.enableBody = true; platforms.setAll('body.immovable', true); ground.scale.setTo(2, 2); ground.alpha = 0; //used this to make the ground transparent blue_player = game.add.sprite(-10, game.world.height -490, 'blue_player'); game.physics.arcade.enable(blue_player); blue_player.body.bounce.y = 0.2; blue_player.body.gravity.y = 300; blue_player.body.collideWorldBounds = true; blue_player.animations.add('idle', [0, 1, 2], 2, true); blue_player.animations.play("idle"); game.state.start("updateState"); } }; and updateState.js: I have also had var updateState error as undefined, witch does not happen in the tutorials I've used. Though this does not happen now with the code you see here. console.log("update is working"); var updateState = { update: function() { game.physics.arcade.collide(blue_player, platforms); } }; Thanks for reading, hope you can set me straight.
  14. Tufan

    About the stage

    I get this error when restarting Game state. This line causing the error: this.player.healthbar = new HealthBar(this, {x:this.player.x, y:this.player.y-25, height:5, width:50}); It's all fine if i call world.removeAll in the state.shutdown function. shutdown: function(){ this.world.removeAll(); } Why am i have to call world.removeAll after switching states? Shouldn't it clear the game world itself when game.state.start is called? Docs says "but not the Stage, so if you've added your own objects to the Stage they will need managing directly" Is healthbar added to the Stage? If so, What is the stage? I'm using phaser.healthbar plugin to create health bars.
  15. Being rather new to Phaser I have run into a problem that have halted my progressed. The code in question is as following. //Gun this.weapon = game.add.weapon (20, 'missile'); this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; this.weapon.bulletAngleOffset = 0; this.weapon.fireAngle = 0; this.weapon.bulletSpeed = 400; this.weapon.fireRate = 100; this.weapon.trackSprite(sprite, 90,52) And it gives me the following error TypeError: Phaser.Weapon is undefined In my test project I have the exact same piece of code, the only difference is that my current project uses game states and the previous is contain in a single .js file Anyone had a similar error and/or have a solution? I have added the project as a .rar file in case that helps Heli-cop hero opgave_2.rar
  16. I'm doing a round based game. So after you've killed so many enemies it'll pop up, "Round 1", after some more, "Round 2" and so on. The amount of enemies doesn't change it's just the round that increases after you've killed say 20 enemies. I have a current variable at the top of my game.js file var currRound = 1; var EnemiesKilled = 0; Every time I kill an enemy I increment up the variable then in one of the collision handlers I do if EnemiesKilled == 20 then show some text newLevel.setText("Woo!! Round " + currRound + "!"); and restart the round via setTimeout(function() { game.state.start(game.state.current); }, 1000); The thing is, it whipes the variable of EnemiesKilled. How can I keep that variable so I always know how many enemies the player has killed?
  17. Hi all, currently I got problem that I have a websocket thread to communicate with the server. and the game object is also start in the process, the situation is like this. when I got the response: A from the server, I will change the game to a new state by game.state.start('NEW STATE'); and then I will get the response: B, C from server, then I need to run some functions defined in the new state, like this game.state.callbackContext.function_in_new_state(); but it is not working, then I loged the state game.state.current I found that the current state is still the OLD ONE. I know the state change need some time, BUT is PHASER provide any callback method when the current state changed to another one, thx everyone.
  18. Hello :), i am facing an the following issue: How do i preserve my sprites, buttons etc. after switiching back from another state. Example: 1. First State: I have several sprites, which i drag an drop around, draw some lines etc. The moment i click on a certan button State 2 is loaded up Sso when i go back to State 1 from State 2,everything is resetted and my sprites are at the wrong place etc. Question: What can i do about it? greets and thanks
  19. Hi, I am new to game development and am trying to make a game where one stage has 6 characters and user can choose any number of characters from here and only those characters will be loaded in next stage. I am using different js files for each stage. Please help. Thanks in advance
  20. Hi there, Can anyone tell me what I'm doing wrong here? I just need an array of sprites with inputOver events. Right now it works on the first load of the menu and not thereafter. It needs to load 4 times in the game. Currently I'm doing this: var createPanels = function(){ // draw panels for (var i = 0; i < 4; i++) { lightPanels[i] = game.add.sprite(ProgressModel.gameRooms[i].x * game.width, ProgressModel.gameRooms[i].y * game.height, 'room-light-' + (i + 1)); lightPanels[i].name = i; lightPanels[i].inputEnabled = true; lightPanels[i].events.onInputOver.add(over, this); lightPanels[i].events.onInputOut.add(out, this); lightPanels[i].events.onInputDown.add(selectRoom, this); lightPanels[i].events.onInputUp.add(Up, this); } }; How should you create sprites in an array with events that are reusable on subsequent state loads? There are no errors, the inputOver event just doesn't fire (the input down works fine every time) Any input is much appreciated. Thanks, H
  21. Hay guys, trying to learn states and i've run into a problem. I've got this function. And when it is called, i need it to create some text. States and breaking my phaser game into several files is a first for me and i cant for the life of me figure this out. I need to create some text from the animationPass function, but i get this error: Uncaught TypeError: Cannot read property 'text' of undefined -- of line 7, and thats where the create introText line is. in my intro.js i've got function animationPass() { introText = this.add.text(320, 240, 'Write some text'); //i've tried this.introText - but that didnt work either. } var introMap = function (game) { var introText; } introMap.prototype = { create: function () { animationPass(); }, update: function () { } } And this has worked fine so far. Infact i've used this structure in another file and it works just fine there. Here i get however Uncaught TypeError: Cannot read property 'text' of undefined -- of line 7, and thats where the create introText line is. My preload.js looks like this preload = function (game) { WebFontConfig = { google: { families: ['Press Start 2P'] } }; } preload.prototype = { preload: function () { this.load.spritesheet('intro', 'img/introAnim.png', 172, 124, 25); }, create: function () { this.game.state.start("introMap"); } } I humbly ask for your assistance. And i'm sorry if the answer is obvious. I would not ask if i hadn't spend a great deal of time trying to figure out the answer myself.
  22. I would like to prevent players from switching to any game state by typing "game.state.start('name');" into the console. Has anyone found a way to prevent this from happening? Imagine you have a login-screen and any user can just type "game.state.start('play');" into the console and skip straight into the game. I have already tried using anonymous functions and closures but the problem is that the other states such as BootState, MenuState, GameState etc cannot access the game object created from new Phaser.game. I cannot be the only one who's worried that users can simply skip any game state by typing one line into the console. How have others dealt with this security breach? I tried googling but couldn't find any posts about this whatsoever. Thanks in advance for all answers!
  23. when i switch from menu state to game state and return at menu, the animation of star field that i have created is stopped. i post my code here: create: function(){ //create a 100 stars in random position this.sprites = this.game.add.spriteBatch(); for (var i = 0; i < this.max; i++) { this.xx[i] = Math.floor(Math.random() * this.game.width); this.yy[i] = Math.floor(Math.random() * this.game.height); var star=this.game.make.sprite(this.xx[i], this.yy[i], 'star'); this.sprites.addChild(star); this.stars.push(star); } // [....] other code }, update: function() { // shift the star at left for (var i = 0; i < this.max; i++) { this.xx[i] -= this.speed; if (this.xx[i] < 0) //return at right and give a new random y { this.xx[i] = this.game.width; this.yy[i] = Math.floor(Math.random() * this.game.height); } this.stars[i].x=this.xx[i]; this.stars[i].y=this.yy[i];//apply a new coords } } }; function play(obj) { obj.game.state.start('Game'); }
  24. 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.
×
×
  • Create New...