Search the Community
Showing results for tags 'Objects'.
-
I'm just curious what are regarded as best practices to avoid the dreaded GC pauses that can mess with the framerate of your game. I've only made some really simple games so I don't really have that much experience with this. Generally the way I've made objects when outside gamedev type situations is pretty close the Crockford-style way of making objects by have a factory function that returns an object literal with functions that closures that refers to variables inside functioning as private variables. (Technically I use TypeScript, but I don't really need to get into the types for this discussion.) const createObject = (someArg) => { let variable = someArg; return { changeVariable: (change) => { variable += change; }, getVariable: () => variable, }; }; const o = createObject(42); o.getVariable(); // 42 o.changeVariable(3); o.getVariable(); // 45 From a purely programming ergonomics perspective this is the way of writing objects I find the most comfortable (not trying to convince anyone else here, this is just my preference). However, I've read many places that aspects of this can be bad for performance (even Crockford admits this about his own pattern). in typical JavaScript programming this seems fine to me, but for games I worry that I'm limiting myself in performance which can lead to slowness or limits to for exampe how many objects I can have running in my game. This has made me think that I maybe ought to be using ES6 classes (or something else that uses prototypes) instead of my closure based approach. Also, maybe I should use object pools? Or hell, maybe even entity-component-systems? Suddenly this stuff seems really complicated (I'm _almost_ wishing I could just use malloc and free, haha). How do you people deal with this? How do you balance ease of testing out ideas while having an reasonable path towards optimization if needed be? I'm generally thinking of using Pixi.js for graphics (hence why I posted in this forum), and Matter.js for the times I want a dedicated physics engine. Sorry for the long post! I'll be very grateful for any thoughts on this!
- 3 replies
-
- gc
- garbage collector
-
(and 4 more)
Tagged with:
-
Hello, I have an issue which keeps me stuck and I could not yet figure it out after being stuck for quite some time. I have a simple game in which obstacles ( spirtes of other cars) drop down from the top of the screen and I am trying to avoid those with my own car not to crash into them. The issue is that on some mobile devices the cars drop WAY faster than on my own device, I tested this from several different phones, the velocity differs depending on the phone, on some the obstacles drop faster on some they drop really slow. What oculd cause such an issue? I can provide code if it helps. Thanks,
-
Hi all, I'm working on my first Phaser based game, online documentaion is very useful, but I can't find informations about destroying instances. function Enemy(game, layer, x, y, enemyStyle){ var newX = 0; var newY = 0; switch(enemyStyle){ case 'big_guy': newX = x; newY = y-68; break; case 'fast_guy': newX = x; newY = y-24; break; } var mySprite = game.add.sprite(newX, newY, decoType); mySprite.anchor.setTo(0.5, 0.5); layer.add(mySprite); } Enemy.prototype.delete = function(){ mySprite.destroy(); } Here I can destroy the enemy sprite, but not the enemy instance..
-
When programming my HTML5 2d game I noticed that using the new operator during game play can be quite expensive sometimes if many objects are created. So I wonder what is good practice here? When you implement your game do you always create the objects that are going to be dynamically used from start (for objects such as particles, ammunation, explosions etc), and then reuse them during game play?
-
I am trying to make a platformer mod of the first tutorial platformer, and this is my first time working with phaser. I am attempting to have diamonds spawn from the sky on a timer, that the player may collect. Everything except the spawning of diamonds seems to be working correctly, my code is as follows: <!--The sprites and some of the movement controls for this game come from this tutorial: https://phaser.io/tutorials/making-your-first-phaser-game --> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Phaser - Making your first game, part 9</title> <script type="text/javascript" src="js/phaser.min.js"></script> <style type="text/css"> body { margin: 0; } </style> </head> <body> <script type="text/javascript"> //sets up a game, setting the area of play and loading it in var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); //loads what will be needed for the game before the game starts function preload() { game.load.image('sky', 'assets/sky.png'); game.load.image('ground', 'assets/platform.png'); game.load.image('diamond', 'assets/diamond.png'); game.load.spritesheet('dude', 'assets/dude.png', 32, 48); } //here I can set variables that can be accesses by create, //much like putting in variables before calling them in unity var player; var platforms; //directional keys to use for movement var cursors; var score = 0; var scoreString = ''; var scoreText var scoreText; var firingTimer = 0; //uses the preloaded items and other lines of code to make the beef of the game function create() { game.add.sprite(0, 0, 'sky'); //enables arcade physics game.physics.startSystem(Phaser.Physics.ARCADE); diamonds = game.add.group(); diamonds.enableBody = true; diamonds.createMultiple(30, 'diamond'); diamonds.setAll('anchor.x', 350); diamonds.setAll('anchor.y', 350); diamonds.setAll('outOfBoundsKill', true); diamonds.setAll('checkWorldBounds', true); // The score scoreString = 'Score : '; scoreText = game.add.text(10, 10, scoreString + score, { font: '34px Arial', fill: '#fff' }); //background //will contain the ground platforms = game.add.group(); //any object in the platforms group will have a body platforms.enableBody = true; // Here is where the ground is created var ground = platforms.create(0, game.world.height - 64, 'ground'); // Scale it to fit the width of the game (the original sprite is 400x32 in size) ground.scale.setTo(2, 2); // This stops the ground from falling away when you jump on it ground.body.immovable = true; // The player and its settings player = game.add.sprite(350, 400, 'dude'); // We need to enable physics on the player game.physics.arcade.enable(player); // Player physics properties. player.body.bounce.y = 0.2; player.body.gravity.y = 600; player.body.collideWorldBounds = true; //Our two animations, walking left and right. player.animations.add('left', [0, 1, 2, 3], 10, true); player.animations.add('right', [5, 6, 7, 8], 10, true); //controls cursors = game.input.keyboard.createCursorKeys(); } function update() { console.log(firingTimer); // Collide the player with the ground game.physics.arcade.collide(player, platforms); // Reset the players velocity (movement) //this means that if no keys are pressed, the player will //remain in place player.body.velocity.x = 0; //if the left arrow is pressed, add velocity to the player and play an animation if (cursors.left.isDown) { // Move to the left player.body.velocity.x = -400; player.animations.play('left'); } //if the right arrow is pressed, add velocity to the player and play an animation else if (cursors.right.isDown) { // Move to the right player.body.velocity.x = 400; player.animations.play('right'); } else //if no keys are pressed. animation is set to one constant frame //and no velocity is added { //Stand still player.animations.stop(); //sets player's frame to the one facing forward player.frame = 4; } // Allow the player to jump if they are touching the ground. if (cursors.up.isDown && player.body.touching.down) { player.body.velocity.y = -350; } if (game.time.now > firingTimer) { //enemyfires generateDiamond(); } game.physics.arcade.overlap(diamonds , player, aquireDiamond, null, this); } function generateDiamond(){ diamond = diamonds.getFirstExists(false); if(diamond){ diamond.reset(350, 350); firingTimer = game.time.now + 2000; diamond.body.gravity.y = 200; } } function aquireDiamond(player,diamond){ diamond.kill (); score+=100; scoreText.text = scoreString + score; Debug.log //if time = certain amount then spawn diamond in random //position above screen and let it fall, it will not stay on the ground } </script> </body> </html>
-
Hi all. I'm trying to return an array of objects loaded by the Mesh Importer for later use. I would like to be able to call a function to load my objects and outside of the function, affect & change each one of them OUTSIDE of the function. Here is the small demo I made :: http://www.babylonjs-playground.com/#1QJUDF#3 Thank you! <3 Mythros
-
Hi! I can access the x parameter on this.draw() function, why it doesn't work on this.updateRotation()?? After I create a Shooting Module on my game loop I can access the getX(). What I am missing? function ShootingModule(_canvas){ this.x = 200; this.y = 500; this.radius = 16; this.rotation = 0; this.canvas = _canvas; this.color = "blue"; this.draw = function (context){ context.beginPath(); context.translate(this.x, this.y); context.rotate(this.rotation * Math.PI / 180); context.arc(0, 0, this.radius, 0, Math.PI * 2, true); context.fillStyle = this.color; context.fill(); context.fillRect(-6, -this.radius -6, 12, 12); context.stroke(); context.setTransform(1, 0, 0, 1, 0, 0); }; this.updateRotation = function(e){ console.log(this.x); this.rotation = Math.atan2(e.clientY - this.y, e.clientX - this.x); }; this.update = function(){ }; this.getX = function(){ return this.x; }; } In my main loop script: playerShootingModule = new ShootingModule(canvas); canvas.addEventListener('mousemove', playerShootingModule.updateRotation, true);
-
I have a two player mini game, with all the main logic happening in this: function SpriteDoObj(player){ // global function this.player = player; this.atk = function(opponent) { this.opponent = opponent; if (this.player.overlap(opponent)) { //call miss sound here console.log("miss"); return; } else if (this.isSameAtkPosition(opponent)) { //call block sound console.log("block"); return; } else { console.log("hit!"); //call damage sound opponent.health --; } }; } //has been simplified And I make two instances of SpriteDoObj with: this.blueSpriteDo = new SpriteDoObj(blue_player); this.redSpriteDo = new SpriteDoObj(red_player); //.. also the players are made like this: this.players = this.game.add.physicsGroup(); var red_player = this.players.create(window.innerWidth, this.world.height - 490, 'red_spritesheet'); var blue_player = this.players.create(0, this.world.height - 490, 'blue_spritesheet'); And the atk function is called like this: if (blue_keyMap.atk.isDown) { this.blueSpriteDo.atk(this.redSpriteDo); //the parameter for the atk function //passes the opposite player, that becomes the opponent } The error is phaser.js:47751 Uncaught TypeError: displayObject.getBounds is not a function And I'm not sure why this is happening, mayhaps something to do with how I'm passing the objects around, but it looks good to me - though I'm a noob. Any Ideas?
- 2 replies
-
- phaser
- javascript
-
(and 1 more)
Tagged with:
-
I am creating a Pacman game in JavaScript and have ran into a problem. I am trying to implement the ghost's movement. On each loop, I record the Tile Position of the ghosts var ghostX = Math.round(ghost.x / map.tileWidth); var ghostY = Math.round(ghost.y / map.tileHeight); There are four possible directions in which a ghost can move var moves = [ { 'direction': 'left', 'position': map.getTileLeft(0, ghostX, ghostY).x, 'distance': Math.sqrt(Math.pow((map.getTileLeft(0, ghostX, ghostY).x - pacmanX), 2) + Math.pow((map.getTileLeft(0, ghostX, ghostY).y - pacmanY), 2)), 'available': levelState.pathLeftAvailable(ghostX, ghostY) }, { 'direction': 'right', 'position': map.getTileRight(0, ghostX, ghostY).x, 'distance': Math.sqrt(Math.pow((map.getTileRight(0, ghostX, ghostY).x - pacmanX), 2) + Math.pow((map.getTileRight(0, ghostX, ghostY).y - pacmanY), 2)), 'available': levelState.pathRightAvailable(ghostX, ghostY) }, { 'direction': 'up', 'position': map.getTileAbove(0, ghostX, ghostY).y, 'distance': Math.sqrt(Math.pow((map.getTileAbove(0, ghostX, ghostY).x - pacmanX), 2) + Math.pow((map.getTileAbove(0, ghostX, ghostY).y - pacmanY), 2)), 'available': levelState.pathUpAvailable(ghostX, ghostY) }, { 'direction': 'down', 'position': map.getTileBelow(0, ghostX, ghostY).y, 'distance': Math.sqrt(Math.pow((map.getTileBelow(0, ghostX, ghostY).x - pacmanX), 2) + Math.pow((map.getTileBelow(0, ghostX, ghostY).y - pacmanY), 2)), 'available': levelState.pathDownAvailable(ghostX, ghostY) } ]; As you can see, I thought the best data structure for this would be an array of objects. Each move has several properties including the name of the direction, how far the move will place the ghost from Pacman, and whether it's a legal move. To find the closest tile, you use the distance formula. This is the square root of the squares of the sums of the x and y coordinates. I then created two variables to represent the closest and furthest tiles. This is where I received the error message var closestTile = moves.filter(m => m.available).sort((a,b) => a.distance - b.distance)[0].direction; var furthestTile = moves.filter( m => m.available).sort((a,b) => b.distance - a.distance)[0].direction; I need to find only legal moves, so it was necessary to filter() the array to find only those moves. The arrays then needed to be sorted by their distance. The first such element will be the result of the variable. But it couldn't find the direction property. The movement function is finished out like this var ghostVelocity = levelState.getGhostVelocity(); this.game.physics.arcade.collide(ghost, wallLayer, function() { var ghostDirection; if (ghost.direction == 'up' || ghost.direction == 'down') { ghost.y += ghost.direction == 'up' ? 1 : -1; if (ghost.vulnerable) { ghostDirection = furthestTile; } else { if (ghost == redGhost) { ghostDirection = closestTile; } else { ghostDirection = Math.random() > 0.5 ? 'left' : 'right'; } } ghost.body.velocity.y = 0; ghost.body.velocity.x = ghostDirection == 'left' ? -ghostVelocity : ghostVelocity; } else if (ghost.direction == 'left' || ghost.direction == 'right') { ghost.x += ghost.direction == 'left' ? 1 : -1; if (ghost.vulnerable) { ghostDirection = furthestTile; } else { if (ghost == redGhost) { ghostDirection = closestTile; } else { ghostDirection = Math.random() > 0.5 ? 'up': 'down'; } } ghost.body.velocity.x = 0; ghost.body.velocity.y = ghostDirection == 'up' ? -ghostVelocity : ghostVelocity; } ghost.direction = ghostDirection; }, null, this); As you can see, I am setting the ghost's direction property based on the closest tile to pacman. For reference, here are the four functions that determine whether a direction is available. There doesn't seem to be a problem here. pathRightAvailable: function(x, y) { return [x, x + 1, x + 2].every(function(xPosition) { return !map.hasTile(xPosition, y, 0); }); }, pathLeftAvailable: function(x, y) { return [x, x - 1, x - 2].every(function(xPosition) { return !map.hasTile(xPosition, y, 0); }); }, pathUpAvailable: function(x,y) { return [y, y - 1, y - 2].every(function(yPosition) { return !map.hasTile(x, yPosition, 0); }); }, pathDownAvailable: function(x,y) { return [y, y + 1, y + 2].every(function(yPosition) { return !map.hasTile(x, yPosition, 0); }); }, I've been working on this problem for some time but have ran into trouble. Any help is greatly appreciated
-
Hello! I am trying to create a grid of bar elements (to form some kind of net) and I was wondering if there is a way to group these bars, so when I want to move the net, all of the children objects would move also. EXAMPLE: var bar1 = new BABYLON.Mesh.CreateBox(name, 1, scene); var bar2 = new BABYLON.Mesh.CreateBox(name, 1, scene); var bar3 = new BABYLON.Mesh.CreateBox(name, 1, scene); <-- how do I group bar1, bar2, bar3 so that I could use : group.position.x = 10;
- 11 replies
-
So i'm just trying to make a simple collision between falling objects and a players sprite. Its nothing complicated. I'm trying to use the game.physics.arcade.overlap() function. Here is my code: The Player class -> export class Player{ game: Phaser.Game; player: Phaser.Sprite; constructor(game:Phaser.Game){ this.game = game; this.player = this.game.add.sprite(400, 520, "Player"); this.game.physics.arcade.enable(this.player); } create(){ } update(){ if (this.game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { if(this.player.x >= -10){ this.player.x -= 7; } } else if (this.game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { if(this.player.x <= 830){ this.player.x += 7; } } } } The falling objects class -> export class Rock { game:Phaser.Game; rocks: Phaser.Group; constructor(game:Phaser.Game){ this.game = game; } create(){ this.rocks = this.game.add.physicsGroup(Phaser.Physics.ARCADE); this.game.physics.arcade.enable(this.rocks); var x = 10; for(var i = 0; i < 9; i++){ var rock = this.rocks.create(x, this.game.rnd.between(-30,-5), "Rock"); rock.body.velocity.y = this.game.rnd.between(240,300); x += 105; } } update(player){ this.rocks.forEach(this.checkPos, this); } checkPos(rock) { if (rock.y > 800) { rock.y = -100; } } } The Main Game File where i'm using the overlap function -> create(){ this.difficulties = []; this.difficulties.push(new Difficulty(0, 5)); this.difficulties.push(new Difficulty(1, 7)); this.difficulties.push(new Difficulty(2, 9)); this.currentDifficulty = this.difficulties[0]; this.shouldChangeDifficulty = true; this.levelOne = new LevelOne(this.game); this.levelOne.create(this.currentDifficulty); this.currentLevel = this.levelOne; this.player = new Player(this.game); this.player.create(); this.rocks = new Rock(this.game); this.rocks.create(); } update(){ this.player.update(); this.rocks.update(this.player); this.game.physics.arcade.overlap(this.player, this.rocks, this.collisionHandler, null, this); } collisionHandler (player, rock) { console.log("Does it work ?!"); }
-
Hi, my project with BabylonJS is growing day to day. Now, I am going to introduce interaction to my scene. I dont know how can I get this. I would like click to some object and see on screen show information of it. To do this I need to know differents way to interact with objects of scene. Also using a gui, I am interested to hide or show differents elements of my world. Could you show me similar examples? Thanks.
- 2 replies
-
- interaction
- objects
-
(and 1 more)
Tagged with:
-
Hi there, Just a short intro, big fan of BabylonJS library! It got me excited to work on a new project of mine which is my first game. Bear with me now please, as I am fairly new to it, although I'd say I have done my studies on your API and documentation, which looks very attractive. The issue I am having is that when I scale objects bigger, collision goes wrong; Moving objects collide when they have already overlapped. What I expect is that the collision happens as soon as any face of a bounding box touches any face of the other bounding box The more I scale my objects, the worse things look. Please take a look at this playground which is hopefully self explanatory: http://www.babylonjs-playground.com/#10IKS#1 Further worse, uncomment line 29 which scales the ball bigger and see the obvious overlap with the wall. I messed with the methods and properties in the BoundingInfo but nothing helped. It does not look to me that the BoundingInfo is missing something anyway; as you can see, showBoundingBox = true (i.e. the wireframe) reveals nothing unexpected to my eyes. It's the whatever shape/thing that is used to calculate collision is what seems wrong and does not seem to update with the scaled ball. Shouldn't it?
-
Hi, Can someone explain the advantage of creating an object (veggies) and then attaching the game object to veggies ? In many examples, the game object is attached isn't attached to another object. Example 1 var Veggies = Veggies || {}; Veggies.game = new Phaser.Game(480, 320, Phaser.AUTO); Example 2 game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, "ph_game");
-
I have been playing around with Phaser for a couple of days now, but I have been stuck for like the past 3 days on just trying to set up collision with an object layer I set up in Tiled. I am using Arcade Physics here in the main branch. I tried creating the object layer, like you would with any normal tile layer, but the id is always null and errors out. I then did some research and found out that Phaser doesn't support object layers like that. Some objects (treasure chests) I have created in the object layer show up, however. The problem I am having is making the polylines convert to rigid bodies in order to collide with the player. Update: Right now I am using various hacks to simulate something similar, but the original problem still stands. You can see my code here: https://github.com/damianlajara/interactive-portfolio I also tried using P2 Physics in order to use the method `convertCollisionObjects` to convert the polylines into objects, but that did not work either. You can find the code for that in the P2 branch I have set up. Any help would be greatly appreciated!
- 2 replies
-
- objectlayer
- objects
-
(and 2 more)
Tagged with:
-
I'm pretty mew to phaser and am creating a little zombie shooter. The game is all linear on the X axis. Zombies march towards you and you have to shoot them before they get to you. I am using an array of objects to create the zombies and they all spawn at different locations. The issue I am having is that they seem to be moving at different speeds and catch up with each other. I want to have them move in a consistent speed so they don't overlap but stay in a uniformed movement. I can't figure out for the life of me why that might be. Any help would be greatly appreciated. Thank you in advance! You can see the specific code under //Zombie Animation Shamble !!!!!!!!!! var game = new Phaser.Game(800, 600, Phaser.AUTO, 'game', { preload: preload, create: create, update: update }); var Phaser; function preload() { game.load.image('ground', 'assets/images/background.png'); game.load.spritesheet('soldier', 'assets/sprites/Soldier.gif', 64, 64, 7) game.load.spritesheet('zombie', 'assets/sprites/zombiecombo.png', 66, 64, 25) game.load.audio('machinegun', 'assets/sounds/machinegun.mp3'); // game.load.audio('background', 'assets/sounds/electrictiger.mp3') } //Globals var button; var button1; var buttonLabel1; var pDamage; //Begin Create function create() { //Background Image and Audio game.add.sprite(-600,0, 'ground') // var back = game.add.audio('background'); // back.play(); // back.volume = .015 //Objects function Player(name, animate, health, bullets, sprite, dmg){ this.name = name, this.animate = animate, this.health = health, this.bullets = bullets, this.sprite = sprite, this.dmg = dmg } var Soldier = new Player( "", "", 100, 5, game.add.sprite(500, 440, 'soldier'), pDamage ) function Npc(health, sprite){ this.health = health, this.sprite = sprite } //Start Horde/Create new NPC var horde = [] for(var x = 0; x<=4; x++){ var z = [-215, -186, -146, -87, -45] var Zombie = new Npc( 25, game.add.sprite(z[x], 440, 'zombie') ) //Zombie Animation Shamble !!!!!!!!!! var shamble = Zombie.sprite.animations.add('shamble', [0,1,2,3,4,5,6,7,8]); Zombie.sprite.animations.play('shamble', 10, true); game.add.tween(Zombie.sprite).to({ x: game.width }, 15000, Phaser.Easing.Linear.None, true); //Horde array horde.push(Zombie) }; //GUI/HUD var drawActionMenuBorder; var bmd = game.add.bitmapData(352, 152); bmd.ctx.beginPath(); bmd.ctx.rect(0, 0, 352, 152); bmd.ctx.fillStyle = '#8e8e8e'; bmd.ctx.fill(); drawnActionMenu = game.add.sprite(650, 50, bmd); drawnActionMenu.anchor.setTo(0.5, 0.5); var drawnActionMenu; var bmd = game.add.bitmapData(350, 150); bmd.ctx.beginPath(); bmd.ctx.rect(0, 0, 350, 150); bmd.ctx.fillStyle = '#1B303D'; bmd.ctx.fill(); drawnActionMenu = game.add.sprite(650, 50, bmd); drawnActionMenu.anchor.setTo(0.5, 0.5); //HealthCount var style = { font: "40px Arial", fill: "#fff", align: "center" }; var healthText = game.add.text(520, 35, Soldier.health, style); //Buttons var buttonStyle = { font: "32px Arial", fill: "#ffffff" }; button1 = game.add.button( 650, 10, null, playerShoot); buttonLabel1 = game.make.text( 0, 0, "Shoot", buttonStyle) button1.addChild( buttonLabel1 ); // var button2 = game.add.button( 650, 60, null, reload); // var buttonLabel2 = game.make.text( 0, 0, "Reload", buttonStyle) // button2.addChild( buttonLabel2 ); //Methods //Fire Weapon w/ Damage function playerShoot(){ //animation var shoot = Soldier.sprite.animations.add('shoot'); Soldier.sprite.animations.play('shoot', 25, false); //Sound var bang = game.add.audio('machinegun'); bang.play(); //Health-Damage change var newZombieHealth; var lastZ = horde.length -1 pDamage = game.rnd.integerInRange(12, 30); newZombieHealth = horde[lastZ].health - pDamage horde[lastZ].health = newZombieHealth //Zed animation death if(horde[lastZ].health <= 0){ var pointX = Zombie.sprite.x -13 var pointY = Zombie.sprite.y console.log(pointX, pointY) var zDie = this.game.add.sprite(pointX, pointY, 'zombie') zDie.animations.add('zDie', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14,15,16,17,18,19,20,21,22,23,24], false); zDie.animations.play('zDie'); horde[lastZ].sprite.kill() horde.splice(lastZ, 1) console.log(horde) } } //Dump Bin // function reload(){ // if(Soldier.bullets>0){ // var magazine = Soldier.bullets - 1 // Soldier.bullets = magazine // } else { // button1.visible = false // } // } } //End create function update(){ }
-
I built a simple game using phaser, but didn't use multiple game states. The game had only one screen and no states! It was all poorly done. So now I'm learning game states. In this code snippet, taken from a phaser game https://github.com/alexdantas/ludum-dare-29/blob/master/js/states/play.js, we have, for example, a line consisting of this.game.camera.setBoundsToWorld(). I know how this works, but i'm having trouble knowing who is this here. I know this in OOP refers to the "owner" of the function, but in this case, who is it? Another doubt I'm struggling with is, where does the .game.camera.setBoundsToWorld() comes from? Is it from when Phaser initializes a new state? When it start a new state, does it create a new "main state", which in this case is what the "this" refers to, and add attributes/methods to it? Like this game.camera.setBoundsToWorld() method? function Play() {} Play.prototype = { create: function() { this.game.physics.startSystem(Phaser.Physics.ARCADE); this.game.stage.backgroundColor = '#000'; // initialize game variables this.cash = 0; this.chunkGroup = this.game.add.group(); this.nextChunkY = 0; this.game.world.bounds.x = 0; this.game.world.bounds.height = 1024; this.game.camera.setBoundsToWorld(); this.lastChunkIndex = 0; this.tephra = this.game.add.group(); this.rocks = this.game.add.group(); this.gems = this.game.add.group(); this.carrots = this.game.add.group(); this.lastChunk = null; this.chunkIndex = 0; this.generateChunk(); this.generateChunk(); }, }
-
For visualisation: (http://imgur.com/GFRm4hQ) Hi HTML5 Game Devs Forum. Please bear with my beginner-ish questions! Project aim: A simple 'game' where the user chooses between two options (which highlights their selection inside an ellipse) then locks in their answer. My issue(s) with my current code: It works, but it's pretty bad. Basically everything is duplicated which is obviously poor coding, issue is, I don't know how to use JS objects in concert with Phaser, or how to check it if it were an object, and what I've googled either doesn't look right or goes over my head massively. Normally i think i'd want to use an object with some attributes, ala: var button = { sprite = blah; thecorrectanswer = yes/no; currentlyselected = false} etc, and then i'd be able to have a bunch of them if i wanted. Because currently I'm limited to two, and it's straight painful to look at. Similarly, the 'selection ellipses' are just shown/hidden based on clicks. Ideally i think this'd be better if it was a sub-function(terminology?) of the question object that drew an ellipse if it was selected, however when i muddled with .graphics in Phaser to draw an ellipse, it wouldn't come on screen when i toggled it's visibility - do i need an update function (is it a loop that runs continuously?) and get it in there? tl;dr: I can see my code is poorly styled, not very extendable/generalisable, but I don't know enough about JS/Phaser to fix: Can objects (and HTML5gamedev.com) be my saviour here? var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });var text;var counter = 0;var currentselection = "";var correctselection = "option1";function preload () { game.load.image('option1','assets/option1.png'); game.load.image('option2','assets/option2.png'); game.load.image('selected','assets/circled.png'); game.load.image('checkbutton','assets/checkbutton.png');}function create() { game.stage.backgroundColor = '#182d3b'; // This creates a simple sprite that is using our loaded image and // displays it on-screen and assign it to a variable var o1_xpos = game.world.centerX-200; var o1_ypos = game.world.centerY; var option1 = game.add.sprite(o1_xpos, o1_ypos, 'option1'); option1selected = game.add.sprite(o1_xpos, o1_ypos, 'selected'); option1selected.visible = false; var o2_xpos = game.world.centerX+200; var o2_ypos = game.world.centerY; var option2 = game.add.sprite(o2_xpos, o2_ypos, 'option2'); option2selected = game.add.sprite(o2_xpos, o2_ypos, 'selected'); option2selected.visible = false; // Moves the image anchor to the middle, so it centers inside the game properly option1.anchor.set(0.5); option2.anchor.set(0.5); option1selected.anchor.set(0.5); option2selected.anchor.set(0.5); // Enables all kind of input actions on this image (click, etc) option1.inputEnabled = true; option2.inputEnabled = true; text = game.add.text(250, 16, '', { fill: '#ffffff' }); text.anchor.set(0.5); //Assign callbacks onclick option1.events.onInputDown.add(option1onclick, this); option2.events.onInputDown.add(option2onclick, this); //Check Button button = game.add.button(game.world.centerX, 500, 'checkbutton', checkbuttonClick, this, 0, 0, 0); // Moves the image anchor to the middle, so it centers inside the game properly button.anchor.set(0.5); }function option1onclick () { //text: debug purposes only text.text = "You clicked option1"; option1selected.visible = true; option2selected.visible = false; currentselection = "option1";}function option2onclick () { //text: debug purposes only text.text = "You clicked option2"; option1selected.visible = false; option2selected.visible = true; currentselection = "option2";}function checkbuttonClick() { if (currentselection != ""){ if (currentselection === correctselection){ text.text = "CORRECT"; //Do other 'on correct' actions here } else { text.text = "INCORRECT"; } } else { //do nothing because nothing has been selected }}
-
So I have 2 classes. A & B. When a specific event occurs in A, a method in B is called. I don't want to create objects in the classes. How else would you do it?
-
Hi, I've come from an OOP style background with AS3, etc. I'm struggling to work out how to groups things together (kind of like a movieclip in flash). So basically i want to create an object, which will have certain values i can access, but also have created several sprites, and bitmaptext associated with it. Example of how i want to create my object: createNewUpgradeItem:function(myNumber){ var upgradeItem = new UpgradeItem(this, 25, 200+i*55, GAME_NAME.UpgradesAvailable.name, GAME_NAME.UpgradesAvailable.description, GAME_NAME.UpgradesAvailable.upgradePrice, GAME_NAME.UpgradesAvailable.priceMultiplier, GAME_NAME.UpgradesAvailable.sMultiplier, GAME_NAME.UpgradesAvailable.cMultiplier, i%4); GAME_NAME.upgradeMenu.add(upgradeItem); // Doesn't Work upgradeItem._background.events.onInputDown.add(function(){UpgradeItemUpdate(this,upgradeItem);console.log(upgradeItem._name)},this); }, // Where 'i' would be a count (in a for loop) to create several objects. And UpgradesAvailable[] is an array of information to be passed. This works fine i believe and it creates the objects fine and puts them on screen,etc. What i want to do is have this upgradeItem added to a Group (say MenuGroup), so I would have thought something like the following would have worked: GAME_NAME.upgradeMenu.add(upgradeItem); But it doesn't seem to like it. My UpgradeItem code consists of some things, for example: var UpgradeItem = function(game, x, y, upgradeItemName, upgradeDescription, upgradePrice, price, speed, cSpeed, bNumber){ this._name = upgradeItemName; this._description = upgradeDescription; this._upgradePrice = upgradePrice; this._pMultiplier = price | 1; this._sMultiplier = speed | 1; this._cMultiplier = cSpeed | 1; this._active = false; this._backgroundNumber = bNumber | 1; this._upgradeItemGroup = game.add.group(); GAME_NAME.upgradeMenu.add(this._upgradeItemGroup); switch(bNumber){ case 0: this._background = game.add.image(x+10, y+36, 'uBackground1'); break; case 1: this._background = game.add.image(x+10, y+36, 'uBackground2'); break; default : this._background = game.add.image(x+10, y+36, 'uBackground1'); break; } this._background.inputEnabled = true; this._background.input.useHandCursor = true; this._background.anchor.setTo(0); this._upgradeItemGroup.add(this._background); this.UpgradeItemName = game.add.bitmapText(x+30, y+48, 'Lobster',this._name,26,this._upgradeItemGroup); this.UpgradeItemName.anchor.setTo(0); this.UpgradeItemDescription = game.add.bitmapText(x+180, y+48, 'Lobster',this._description,26,this._upgradeItemGroup); this.UpgradeItemDescription.anchor.setTo(0); } You can also see from my code here that i'm trying to group the 'assets' (the text and sprites) into a seperate group. Am I missing something really simple here? Thanks for looking
-
I have a game with a MainMenu state and a Play state. I want to keep my animated background without reloading it (the animation should loop without interruptions) when I change from MainMenu state to Play state. How can I do this?
-
Hey, I was wondering if it's possible to use either CSS, Canvas, HTML or JavaScript to draw elements for a game (like blocks, characters, etc..) or would I have to use a pre-made image. If this has already been answered, please direct me to the proper thread/website. I'm self-taught so a lot of examples and "dumbing down" is greatly appreciated! Thanks again in advance.
-
Hi everyone, Here's my 'attempt' in puzzle games - a Construct 2 game called 'Hidden Objects: Pirate Treasure' Try it here: http://www.m.flashfooty.com/games/hidden-objects-pirate-treasure/ This is a free, kids friendly, 'hidden Objects' game in which your seek and find items within the given time. Do not worry - this game doesn't punish mistakes: time is only important to get better result, that is - more 'stars' on each level. The game play is simple: Find a series of hidden objects in a scene! Seek only objects that are shown in the bottom of the screen - with every mistake you'll lose some time. The complete 'Construct 2' project is also for sale, so you can make your own 'hidden objects' game based on it: https://www.scirra.com/store/games-with-source/hidden-objects-pirate-treasure-848
-
Hello Im doing the game like arkanoid. The problem is when I try to move the bar with physics. When the bar has collided with the wall it lose the path and don't move straight to left to right. When I also try with moveWithCollisions() it works bad when the bar collide with the ball. How can I resolve this?
-
When creating States I've seen both people using Objects and Functions. I've noticed that in the Phaser Coding Tips all the examples are using Functions. Is there any advantage in using Functions over Objects in this case? I understand that using Functions + prototype is good for when you are creating classes and then instances of those classes, but in this case there is only 1 of each State in a game.