Search the Community
Showing results for tags 'game states'.
-
Hello there, I have 3 files for a phaser game an html, cs and javascript file(excluding phaser.js). I would really appreciate if someone who understands the this.blank format would help me convert to a game where I have a boot state, menu state and play state of the game. I honestly don't know how to do this, this would help me learn more and also help progress me a bit because I haven't been able to successfully transit into this.blank format although I have been given examples which I would say are way more complicated than my game and those examples were missing some parts that would have helped me that I couldn't find. code.js index.html style.css
-
My current project uses game states, and I'm to the point where I have a character that can walk between different levels (states), but in every js file where my individual levels are I have all my code for player movement duplicated in each. I'd like to make my code slimmer and more modular because I'm to the point where I'm getting some slow down/lag in chrome browsers, and I'd like to keep scaling my project and that isn't easy with all of this duplicate code in every state. For reference, the way my project is constructed is based off of this tutorial: http://www.emanueleferonato.com/2014/08/28/phaser-tutorial-understanding-phaser-states/ For example, if this were one of my level states: var theGame = function(game){ spriteNumber = null; number = 0; workingButtons = true; higher = true; score = 0; } theGame.prototype = { create: function(){ number = Math.floor(Math.random()*10); spriteNumber = this.game.add.sprite(160,240,"numbers"); spriteNumber.anchor.setTo(0.5,0.5); spriteNumber.frame = number; var higherButton = this.game.add.button(160,100,"higher",this.clickedHigher,this); higherButton.anchor.setTo(0.5,0.5); var lowerButton = this.game.add.button(160,380,"lower",this.clickedLower,this); lowerButton.anchor.setTo(0.5,0.5); }, clickedHigher: function(){ higher=true; this.tweenNumber(true); }, clickedLower: function(){ higher=false; this.tweenNumber(false); } } How could I add methods to the theGame prototype object from a separate JS file? For this example, I'll like to use the clickedHigher method in a handful of different states, but I don't want to have to go through and edit it in each state. In my actually game I'm going to have up 50 different states and each time I refine my controls or add new mechanics I'd have to go through each state and copy paste. Thanks in advance
-
When running in a game state, executed from an Angular controller and canvas, is it possible to end the game by routing to another angular context. I tried using $location.path("/angular-route") but $location is not defined in the game state. I've got the usual booter, preloader, and game states set up and the problem occurs in the game state. Thanks
-
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); } };
-
Hello, I would like to use game states in my project. I followed this tutorial http://perplexingtech.weebly.com/game-dev-blog/using-states-in-phaserjs-javascript-game-developement. In my project I get the error "Reference error: menuState is not defined". You can download my code in the attachment. Can anybody help me with my problem? I am a beginner, so can you please tell me a solution in an easy way? Thanks! Week 6 - Menu game.zip
- 11 replies
-
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!
-
Trying to understand state handling in Phaser. In this simple example, why does the following code log "Menu State" followed by "Game state" in the console? I would expect it to only write "Menu state", since I have not switched states anywhere in the code. var game; game = new Phaser.Game(800, 600); game.state.add("Menu", state_menu); game.state.add("Game", state_game); game.state.start("Menu"); function state_menu() { console.log("Menu state"); this.update = function () { } } function state_game() { console.log("Game state"); this.update = function () { } }
-
Hello, I've been working on a game for 2 weeks. In this game, there will be several maps / levels (2 atm). I want the player to be able to go from one map to another, and back to the first map again. I'm using one game state for each map with a create function that creates every game object the map needs. So basically it recreates everything when I go back to a map I already visited, and it feels so WRONG ! Do you have any idea on how to improve this ? Is there a way to 'freeze' a state when I change map, and 'unfreeze' it when I go back to it ? Or should I merge those in one huge map ? here's the game so you can have a better idea of what it is (if some assets aren't loaded when the game starts, reload the page. This is an issue i'll be correcting soon).
-
Hi, I am creating a game which is using a dynamic map generation including several separated areas. Each area will have its own specific logic and events. So i was planning to deal with that using states but i am not sure how to structure it since there will be like 30 area type. Any suggestions? thx in advance
- 2 replies
-
- project structure
- game states
-
(and 1 more)
Tagged with:
-
Hi, another question about performance~ I've been busy updating my code to get more performance out of Phaser and CocoonJS. Currently everything runs fine ( stable 55 - 60fps ). Question / Problem When I change States - for example I go from my titlescreen into the mainmenu State: there are a few sprites set up and a few tweenings are done. A few means 3 - 6. During the change into the state the game struggles a little bit - it is lagging and also the tweening is lagging. This happens on all iOS devices (only developing for iOS included normal resolution screens / retina devices / iPad Air). The images which are loaded, the audio and all the stuff is minimzed and optimized. There are no big file sizes which have to be loaded. A few Questions on it - Is there something like a preload for tweens? - Or can I preload a state or something? - Which other issues cause this? All the stuff is preloaded in the "preload" function. My states (example: titlescreen, mainmenu) are out of the "create" function - as an own state, is that correct? because to call everything into the create function themes a little bit overdue - to call an entire game with all the logic etc on start. Any suggestions / improvements?
- 1 reply
-
- phaser
- performance
-
(and 7 more)
Tagged with:
-
I have seen game states being constructed in a few different ways: // the game object is an argument of the constructor, and also property of the statevar state1 = function(game){ this.preload = function(){ this.game.load.image('img1', 'assets/img1.png'); ... } ...};// the state appears to be synonymous with the game objectvar state2 = function(){ this.preload = function(){ this.load.image('img1', 'assets/img1.png'); ... } ...};Both appear to work, though I don't understand why. Could someone enlighten me? Also, are there recommendations as to which one would be better? Or what are their relative pros and cons? (I might be able to answer this myself if I understood why both work!)
-
So, I just started using different states in Phaser to handle the use of Win screens and the like. The problem that I'm having, is that the update function doesn't seem to be recognizing the this.hero at all. It doesn't stop the animation or the hero's velocity when it hits the ground. Similarly the updateCounter function doesn't seem to be running at all. I usually declare my functions as such: var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update, updateTimer: updateTimer});function preload() {} and both the updateTimer and the stopping animation work fine, but I switched to how it is below after I saw a tutorial on how to use different game states. I think this is probably the issue, but I'm not well versed enough in Phaser to know exactly why it isn't working. var gameplay = function(game){};gameplay.prototype = {preload: function(){ this.load.image('ground', 'assets/ground.png'); this.load.spritesheet('hero', 'assets/hero.png', 165, 225);},create: function(){this.game.physics.startSystem(Phaser.Physics.ARCADE);this.game.physics.arcade.gravity.y = 1200;this.ground = this.game.add.tileSprite(0, 250, 480, 70, 'ground');this.game.physics.arcade.enableBody(this.ground);this.ground.body.immovable = true;this.ground.body.allowGravity = false; this.hero = this.game.add.sprite(180, 60, 'hero'); this.hero.animations.add('left',[1,2,3],15,false); this.hero.animations.add('right',[4,5,6],15,false); this.hero.frame=0; //start timer this.currentTimer = this.game.time.create(false); this.currentTimer.loop(Phaser.Timer.SECOND, this.updateTimer, this); this.currentTimer.start();},update: function(){ if(this.hero.body.touching.down && jumpKey.isUp) { this.hero.body.velocity.x=0; this.hero.frame=0; this.hero.animations.stop; }this.game.physics.arcade.collide(this.hero, this.ground);}, updateTimer: function() { counter++; console.log(counter); }var game = new Phaser.Game(605, 385, Phaser.AUTO, 'game');game.state.add('menu', Menu);game.state.add('gameplay', gameplay);game.state.add('winner', Winner);game.state.start('menu');}Anyone know why this isn't working?