Search the Community
Showing results for tags 'Random'.
-
Greetings. I have 5 webpages with games. I want another html5 page to generate 5 random numbers where every number opens one of the game pages. I used to do this on flash with a simple small .swf and embed it in the HTML page. It looks like: variable=random(5); if variable == 1 {open game page 1}; if variable == 2 {open game page 2}; ans so on.. Now I need to do that with clean HTML5, How to do it?
-
hello, I am very new in Phaser2 and I need help in something. this thing is to do something like enemies' generator. My idea is that in a position it is chosen between 2 enemies to be generated, then spent a second, in the same position become another enemy between the two and this way successively... thank you ❤️:c
-
Hi guys, how do you place items(sprites) randomly on your world and ensure that they don't overlap with other already excisting items? Do you check every item or are there functions from the physic engines that support you with that? If there are no built in functions I would do it the following way: 1.) create random placement of sprite 2.) check newly placed items against all excisting items in the world 2.1) No overlapping -> GREAT finish! 2.2) If it overlaps repeat step 1. (abort after X cycles to avoid endless loop and performance spikes if you place them while the game runs) If you do it like this: is there are a global phaser list where I can loop through: a.) all excisting sprites b.) all visible sprites ??? Any other ideas and strategies to place items randomly? Thanks and greetings from a sunny Vienna, Clemens
-
There is a puzzle game at http://www.html5pcode.com/a1ypuzzle.htm The p-code was written in HTML5 JavaScript. The home page is http://html5pcode.com A pattern was made for each puzzle piece. Random numbers were used to make the jagged sides. HTML5 has an image option that allows you to use a pattern like a cookie cutter. The result was an image that could be turned and then placed on the right side of the screen. Random number were used to determine where each piece would be placed. This game is written in a p-code. The p-code is executed by a p-code engine. If you click on PROGRAM in the RED STRIPE at the top, you can view the p-code programs. The p-code engine can execute the programs and it can edit the programs.There is a DATA option that allows you to see the program's data as it is being executed. There is a TRAIL option that allows you to execute the program in small steps. There is an RT, Real Time, option that allows you to change the program as it is executing. There are many YouTube videos that will show you how it works.
-
var game = new Phaser.Game(400, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); //creating score value and onscreen text var score = 0; var scoreText; //creating random spawning place for diamond var diamondX = game.world.randomX(); var diamondY = game.world.randomY(); function preload() { // preload assets game.load.image('sky', 'assets/img/sky.png'); game.load.image('ground', 'assets/img/platform.png'); game.load.image('star','assets/img/star.png'); game.load.image('diamond', 'assets/img/diamond.png'); game.load.spritesheet('baddie', 'assets/img/dude.png', 32, 48); } function create() { // place your assets //enabling Arcade Physics system game.physics.startSystem(Phaser.Physics.ARCADE); //adding a background game.add.sprite(0, 0, 'sky'); //a group containing the ground and platforms to jump on platforms = game.add.group(); //enabling physics for any object in this group platforms.enableBody = true; //creating the ground var ground = platforms.create(0, game.world.height - 64, 'ground'); //scaling to fit the width of the game ground.scale.setTo(2, 2); //stops ground from falling once player jumps on it ground.body.immovable = true; //create five ledges var ledge = platforms.create(-300, 400, 'ground'); ledge.body.immovable = true; ledge = platforms.create(200, 400, 'ground'); ledge.body.immovable = true; ledge = platforms.create(100, 300, 'ground'); ledge.body.immovable = true; ledge = platforms.create(-200, 200, 'ground'); ledge.body.immovable = true; ledge = platforms.create(300, 100, 'ground'); ledge.body.immovable = true; //create the player and its settings player = game.add.sprite(32, game.world.height - 150, 'baddie'); //enabling physics on player game.physics.arcade.enable(player); //giving player a slight bounce player.body.bounce.y = 0.2; player.body.gravity.y = 300; player.body.collideWorldBounds = true; //walking left and right animations player.animations.add('left', [0, 1, 2, 3], 10, true); player.animations.add('right', [5, 6, 7, 8], 10, true); //create group for stars stars = game.add.group(); stars.enableBody = true; //creating 12 stars evenly spaced apart for (var i = 0; i < 12; i++) { //create a star inside of the 'stars' group each 33 px apart var star = stars.create(i * 33, 0, 'star'); //giving it gravity star.body.gravity.y = 20; //giving each star a random bounce value star.body.bounce.y = 0.7 + Math.random() * 0.2; } //create diamond and apply physics diamond = game.add.sprite(diamondX, diamondY, 'diamond'); game.physics.enable(diamond, Phaser.Physics.ARCADE); diamond.body.gravity.y = 25; diamond.body.bounce.y = 0.7 + Math.random() * 0.2; //displays score text on screen scoreText = game.add.text(16, 16, 'Score: 0', {fontSize: '32px', fill: '#000'}); } function update() { // run game loop //collide player and platforms var hitPlatform = game.physics.arcade.collide(player, platforms); //built in keyboard manager cursors = game.input.keyboard.createCursorKeys(); //reset players velocity (movement) player.body.velocity.x = 0; //moving with arrow keys if (cursors.left.isDown) { //move to left player.body.velocity.x = -150; player.animations.play('left'); } else if (cursors.right.isDown) { //move right player.body.velocity.x = 150; player.animations.play('right'); } else { //stand still player.animations.stop(); player.frame = 2; } //allow player to jump if touching ground if (cursors.up.isDown && player.body.touching.down && hitPlatform) { player.body.velocity.y = -350; } //checking for collision with stars and platforms game.physics.arcade.collide(stars, platforms); //checking if player overlaps with star game.physics.arcade.overlap(player, stars, collectStar, null, this); //checking for collision with diamond and platforms game.physics.arcade.collide(diamond, platforms); //checking if player overlaps with diamond game.physics.arcade.overlap(player, diamond, collectDiamond, null, this); } function collectStar (player,star) { //function for updating score for collecting stars //removes star from screen star.kill(); //add and update score for stars score += 10; scoreText.text = 'Score: ' + score; } function collectDiamond (player, diamond) { //function for updating score for collecting diamond //remove diamond from screen diamond.kill(); //add and update score for diamond score += 25; scoreText.text = 'Score: ' + score; } It's my first time trying out Phaser and what I want to do is have the 'diamond' spawn at random locations on the screen. I've managed to get the diamond to spawn on screen, but it doesn't seem to be spawning in different locations when I reload the game each time. I'm assuming that I'd need to put something in the update function, but I need a little help with that part!
-
I would like to create a scoring system in which the coins randomly descended into different places. Sorry if the english is bad (still lurning the language). This is my code. (function () { var game = new Phaser.Game(540, 303, Phaser.AUTO, 'container-game', { preload: preload, create: create, update: update, }); var estrada, player, keys, moedas; function preload() { this.velocidade = 80; // CARREGAMENTO DE IMAGENS game.load.image('background', 'img/background.png'); game.load.spritesheet('boneco', 'img/player.png', 37, 78); game.load.spritesheet('moeda', 'img/moeda.png', 31, 31); } function create() { this.moedas = game.add.group(); game.time.events.loop(5000, this.adicionarMoeda, this); // FISICAS DO JOGO game.physics.startSystem(Phaser.Physics.ARCADE); keys = game.input.keyboard.createCursorKeys(); // BACKGROUND estrada = game.add.tileSprite(0, 0, 540, 303, 'background'); // APLICAÇÕES SOB O PERSONAGEM player = game.add.sprite(252, 200, 'boneco'); game.physics.arcade.enable(player); player.animations.add('pedalar', [0, 1, 2, 3], 10, true); player.animations.play('pedalar'); } function update() { // BACKGROUND INFINITO this.velocidade += 1 * 0.03; estrada.tilePosition.y += this.velocidade / 60; console.log(this.velocidade); // CONTROLES DO PERSONAGEM if (keys.left.isDown) { if (player.x > 172) { player.x -= 5; } } if (keys.right.isDown) { if (player.x < 329) { player.x += 5; } } } function adicionarMoeda() { var moedaX = game.rnd.integerInRange(170, 320); var moeda = game.add.sprite(moedaX, -30, 'moeda'); this.moedas.add(moeda); game.physics.arcade.enable(moeda); moeda.body.velocity.y = this.velocidade; moeda.animations.add('girar', [0, 1, 2, 3, 4, 5, 6, 7], 16, true); moeda.animations.play('girar'); moeda.checkWorldBounds = true; moeda.outOfBoundsKill = true; } }());
-
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>
-
Hello, I'm creating endless style game and I'm planning to reuse already existing sprites instead of creating new ones. My sprites are coming from the top moving towards the bottom of the screen, when they reach bottom I reset their position.y to 0 which brings them back to the top again, but I also wanted them to have random position.x every time they start again from the top, I called this function: obstacles.forEach(function(obstacle){if(obstacle.position.y > this.game.world.height){obstacle.position.y = 0; obstacle.position.x = this.game.rnd.between(0, this.game.world.width);}}) And after trying it out I got this error from the developers console: Is it even posibble to call this.game.rnd.between from the update? If not what is the solution for that? Thanks!
-
I have a bit of code that cycles through my TILED file to find any object I declared as an NPC. I am not sure if this is important, but I wanted to mention how it found the location of the sprite. (And it is designed to work with multiple sprites, but the code fails with a single sprite and multiple sprites) result.forEach(function(element){ this.createFromTiledObjectMove(element, this.doors); //alert (this.doors); }, this); The code above works correctly again it is just for reference on how the next part of the code is found. The code below was INTENDED to have a character mill around. Starts walking right. Stops. Faces forward (with a tiny movement), Stops, Faces left and walks, Stops, Face right and repeat pattern. Hopefully it is easy to read, and I could probably clean it up. The MOTION is fine. He goes back and forth, stopping at each end point. But the animations do not sync correctly. I even tried stopping ALL animations as seen in the code below but eventually he gets stuck in one animation, even though the tween movement continues. Any ideas? //create a sprite from an object WITH ANIMATION! createFromTiledObjectMove: function(element, group) { var sprite = group.create(element.x, element.y, element.properties.sprite); var tweenNPC = this.add.tween(sprite); //I eliminated the randomness for testing - it did work, but same problem //var randomValue = this.rnd.integerInRange(200, 500); //var randomTime = this.rnd.integerInRange(1000, 3000); //var keepRnd = randomValue; var randomTime = 1000; var keepRnd = 40; //copy all properties to the sprite Object.keys(element.properties).forEach(function(key){ sprite[key] = element.properties[key]; sprite.frame = 6; sprite.animations.add('down', [6, 7, 8], 10, true); sprite.animations.add('right', [3, 4, 5], 10, true); sprite.animations.add('left', [9, 10, 11], 10, true); sprite.animations.play('right'); tweenNPC.to({ x: (element.x + keepRnd) }, randomTime, Phaser.Easing.Linear.None, true, 1000, 0, false); tweenNPC.onComplete.add(StopRightandChat, this); function StopRightandChat() { sprite.animations.stop('down'); sprite.animations.stop('left'); sprite.animations.stop('right'); sprite.animations.play('down'); tweenNPC.to({ x: (element.x + 5 ) }, randomTime, Phaser.Easing.Linear.None, true, 1000, 0, false); tweenNPC.onComplete.add(goLeft, this); } function goLeft() { sprite.animations.stop('down'); sprite.animations.stop('left'); sprite.animations.stop('right'); sprite.animations.play('left'); tweenNPC.to({ x: (element.x - keepRnd) }, randomTime, Phaser.Easing.Linear.None, true, 1000, 0, false); tweenNPC.onComplete.add(StopLeftandChat, this); } function StopLeftandChat() { sprite.animations.stop('down'); sprite.animations.stop('left'); sprite.animations.stop('right'); sprite.animations.play('down'); tweenNPC.to({ x: (element.x + 5 ) }, randomTime, Phaser.Easing.Linear.None, true, 1000, 0, false); tweenNPC.onComplete.add(goRight, this); } function goRight() { sprite.animations.stop('down'); sprite.animations.stop('left'); sprite.animations.stop('right'); sprite.animations.play('right'); tweenNPC.to({ x: (element.x + keepRnd ) }, randomTime, Phaser.Easing.Linear.None, true, 1000, 0, false); tweenNPC.onComplete.add(StopRightandChat, this); } }); },
-
I'm making an endless runner and need to generate an obstacle every 2-6 seconds for the player to jump over. I have three obstacle sprites, two along the 'ground' and one hanging from the top of the game window. I was thinking about using a group and randomly selecting a key from that group. sprites must enter from the right and move along y until they go of screen on the right then are killed and re-used again. I've been trying multiple methods to active this but with no luck, its all bit over my head, I'm not even sure whats going wrong. So i'm looking for a bit of direction and advice on how to active this. this is the code (mostly) without my attempts as it got a bit missy. vaultage.game = function() {}; // generate a obstacle at a random time between 2 seconds and 6 seconds this.obstacleRate = game.rnd.integerInRange(2000, 6000); this.obstacleTimer = 0; vaultage.game.prototype = { create : function() { // physics engine this.game.physics.startSystem(Phaser.Physics.ARCADE); this.game.physics.arcade.gravity.y = 1000; // sprites // background this.background = this.game.add.tileSprite(0, 0, this.game.width, 360, 'background'); this.background.autoScroll(-100, 0); // ground this.ground = this.game.add.tileSprite(0, 290, this.game.width, 8, 'ground'); this.ground.autoScroll(-180, 0); // player this.player = this.add.sprite(45, 200, 'player'); this.player.animations.add('run'); this.player.animations.play('run', 15, true); // obstacles this.obstacles = this.game.add.group(); // this.box = this.game.add.group(); // this.pole = this.game.add.group(); // this.cable = this.game.add.group(); // physics on sprites this.game.physics.arcade.enable([this.player, this.ground]); this.ground.body.immovable = true; this.ground.body.allowGravity = false; this.player.body.collideWorldBounds = true; // input cursors = game.input.keyboard.createCursorKeys(); jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); }, update : function() { this.game.physics.arcade.collide(this.player, this.ground); if (jumpButton.isDown && (this.player.body.touching.down)) { this.player.body.velocity.y = -400; } }, shutdown : function() { } createObstacles : function() { } }
-
I'm making an endless runner as my first dive into phaser and I've working on getting the 'obstacles' for my player to jump over. I have 3 obstacles for the player to jump over, 2 on the 'ground' and 1 hanging from the top of the game. My plan is to have one obstacles randomly generated every 2-6 seconds and for them to move towards the player (the player is static except for being able to jump). But I'm not sure how to go about this. Can anyone point me in the right direction? just some sudo code or ideas how you would approach the problem? My repo is https://github.com/craftycal/vaultage if anyone would like to take a look.
-
Just a random one I thought I'd put out there Anyone find it easier to explain things in code, rather than in words? Is that a sign or poor language skills or good coding skills haha.
-
Hello, I want to create a game using Phaser. I want to add sprites randomly, but they shouldn't overlap each other. What is the best practice to achieve this. Here is my code, but I saw overlapping sprites sometimes: var obstacles = []; var items = []; function loadMap () { for (i = 0; i < 100; i++) { var obs = game.add.sprite(game.world.randomX, game.world.randomY, 'obstacle'); game.physics.enable(obs, Phaser.Physics.ARCADE); obstacles.push(obs); } } function loadItems () { for (i = 0; i < 36; i++) { var item = game.add.sprite(game.world.randomX, game.world.randomY, 'item'); game.physics.enable(item, Phaser.Physics.ARCADE); while (checkOverlapMany(item, items) || checkOverlapMany(item, obstacles)) { item.x = game.world.randomX; item.y = game.world.randomY; sleep(80); } items.push(item); } } function checkOverlapMany(sprite, list) { for (var i = 0; i < list.length; i++) { if (game.physics.arcade.overlap(sprite, list )) return true; } return false; }
-
So how can I set random speed for every object, so the acquired speed will stay? Now I have defined speed as constant, but it also increases the speed of every object. SPEED = 3; this.enemies.forEachAlive(function(enemy){ enemy.body.velocity.x += Math.random(SPEED + (SPEED/2)); }); I tried first with Tanks -example style, where is defined max and min speed, but i didn't work.
-
Hi! Does anyone know how I might be able to load a different background each time a game is started? I have three different preloaded backgrounds and would like the game to select a random one each time the game begins. I'm a complete newbie to Phaser and any help/tutorials would be hugely appreciated! Can link code if needed. Thanks!
- 5 replies
-
- Background
- Random
-
(and 3 more)
Tagged with:
-
hey guys, I have a bottom-top game where I have the player navigating through objects. However, I am wondering if it is possible to have the game make minor changes to the x coordinate as opposed to me setting the object to specific coordinates? if you guys could provide any help that would be much appreciated!
- 1 reply
-
- x coordinate
- random
-
(and 1 more)
Tagged with:
-
So I have 3 different characters (using the same sprite at the moment). They are supposed to roam given a predefined path for each. I am using 3 different loops so that they start at different times. I don't want them to start and stop at the same time. Trying to make it as natural as possible and so far I got this http://jsfiddle.net/Batzi/abs191e5/250/ Can someone suggest improvements? I need to make it look as smooth and natural as possible.
-
Hi! I've been at this for hours. I'm trying to make an endless runner game. The idea is that the player is standing still, but the stage is moving, giving the illusion that the player is moving. I want to generate some obstacles at a random distance from each other. Like so: _____@_____@__@________@__ At some point maybe I'd like to set the minimum space between each obstacle but I'm far from there. Here's what I got for now: create() { spawn = 1000; timer = game.time.events.loop(spawn, this.addObstacle, this);},update() { this.updateTimer();},updateTimer: function() { random = Math.floor((Math.random() * 500) + 100); spawn = 1000; timer = game.time.events.loop(spawn, this.addObstacle, this); }....I'm getting Uncaught TypeError: Cannot read property 'reset' of null because I have 10 obstacles and they all pop up on screen at the same time. And there's no 'dead' obstacle for getFirstDead(). Another thing I tried was this: update() { random = Math.floor((Math.random() * 500) + 100); // I think this causes lags and it doesn't feel right this.updateTimer(random);},updateTimer: function(r) { timer.delay(r);}....But here timer.delay is not a function. So far I can spawn obstacles at even intervals with just this line: timer = game.time.events.loop(<Integer>, this.addObstacle, this); P.S. And what is 'this' in this.updateTimer()? I thought it was 'game'. I see it constantly in the API. Guess the creators know pretty darn well its usage.
-
Hey Everyone, Been working on this for a while, and finally ready to release it into the wild! I've created a 'template' for a Random Dungeon Generator using phaser. Please check it out on my blog, where I also have a live demo of it. Feel free to copy, share, etc the code and ideas, and please let me know if you have any changes or improvements, and I would love to see what games people come up with using it
-
I found this function really useful except for picking the last element, which is really really hard in comparison with the other elements, because only the number '1' in a random selection between 0 and 1 with double precision floating points can give the last element. Therefore, the probability of obtaining the last element is too low to be useful. var test = [0,1,2,3,4,5,6,7,8,9];for(i = 0; i< 1000000; i++){ rnd = this.game.rnd.weightedPick(test); if(rnd == 9) console.log(rnd);} PS: The way i solved this is by adding a "dummy"(or a placeholder) element in the last place of the array. So, any suggestion for a clean solution?. Thanks in advance.
- 2 replies
-
- random
- weightedPick
-
(and 3 more)
Tagged with:
-
Hi guys! I'm trying to develop a road with Phaser (My idea is that a car moves for him). How can I do that when the car is outside is slow? My first test: http://codepen.io/jdnichollsc/pen/YPEeYe Any help is greatly appreciated! Regards, Nicholls
-
HI, I'm new to phaser framework, I did some tutorials but these were very basic and do not go towards the game I have to make for a course. I was looking for any help which can help me finish it. I just been able to put some images on screen and add a counter by click on them. Word Memory game Level 1 – A group of words(images) appears for 10 seconds, they then disappear and are replace by another group of words, from this new group of words the player has to identify which of these words are from the last. Input is done by clicking and there is a countdown timer of 1:50minutes+10seconds(memorize) Level 2 & Level 3 – Basically the same but with just more words and less time. My question is: How can I add an array of ImagesID. Make a random of the total of ImagesIDs save the order. And then create/put the images according to the selected order of IDs on screen. I come from php+mysql, C and CSS, I done some JS in the past but never to the point of getting really confortable with it. So if you can please show me some code examples that help with solving this problems. Many Thanks, Deathmachinept
-
- memory game
- random
-
(and 1 more)
Tagged with:
-
Hi, I've been trying to tween my sprite to random x and y co-ordinates in a loop, but after the initial random values are set it just loops between them instead of generating new random values. Anyone know how to solve this problem?? this.add.tween(this.sprite).to( { x: this.rnd.realInRange(-100, 100) }, 1000, Phaser.Easing.Linear.None) .to( { y: this.rnd.realInRange(-100, 100) }, 1000, Phaser.Easing.Linear.None) .loop() .start();
-
I'm making a vertical scrolling platform game using Phaser, but I can't figure out how to create randomly placed platforms to jump on. This is the code I have so far (removed unneccesary stuff): Platformer.Game = function (game) { this._platforms = null; this._platform = null; this._numberOfPlatforms = 15; this._x = this.x; this._y = this.y; }; Platformer.Game.prototype = { create: function (){ this.physics.startSystem(Phaser.Physics.ARCADE); this.physics.arcade.gravity.y = 200; this._platforms = this.add.group(); Platformer.platform.createPlatform(this); Platformer.platform.createPlatform(this); Platformer.platform.createPlatform(this); Platformer.platform.createPlatform(this); Platformer.platform.createPlatform(this); Platformer.platform.createPlatform(this); game.camera.follow(this._player); }, managePause: function () { this.game.paused = true; var pausedText = this.add.text(100, 250, "Game paused. Click anywhere to continue.", this._fontStyle); this.input.onDown.add(function(){ pausedText.destroy(); this.game.paused = false; }, this); }, update: function () { } }; Platformer.platform = { createPlatform: function (game) { var posX = Math.floor(Math.random() * Platformer.GAME_WIDTH * this._numberOfPlatforms * 70); var posY = Math.floor(Math.random() * Platformer.GAME_HEIGHT * this._numberOfPlatforms * 50); var platform = game.add.sprite(posX, posY, 'platform'); game._platforms.add(platform); platform.events.onOutOfBounds.add(this.removePlatform, this); }, removePlatform: function (game) { this._platform.kill(); } } I can get it to work to place them randomly, but the idea of a platformer should be you could actually jump on it... With enough distance but not too much, so I guess not entirely random. Hope you have some ideas! Thanks in advance.
-
In my code im trying to have 3 diff colour blocks spawn in various areas on the screen, but one of the three red blocks spawns exactly on top of a blue one every single time. It makes no sense as I am using a math.random and have even used a game.add.text to make sure that the numbers aren't exactly the same yet it keeps happening. The relevant code is in green, thanks for any help. My code: var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update,});var Rx = Math.random () * 800; // ball spawns in a random placevar Ry = Math.random() * 600; // X and Y coordinate for each colour blockvar Bx = Math.random () * 800; var By = Math.random() * 600;var Gx = Math.random () * 800 var Gy = Math.random() * 600;var text; var colours = ["redBlock","greenBlock","blueBlock"];var colour = colours[Math.floor(Math.random()*2)]; function preload() {cursors = game.input.keyboard.createCursorKeys(); //allows keyboard inputthis.game.load.image("block","assets/block.png");this.game.load.image("redBlock","assets/red.png");this.game.load.image("greenBlock","assets/green.png");this.game.load.image("blueBlock","assets/blue.png");} function create() {this.game.physics.startSystem(Phaser.Physics.ARCADE);this.game.scale.pageAlignHorizontally = true; //centers canvasthis.game.scale.pageAlignVertically = true;this.game.scale.refresh(); for (var i = 0; i < 3 ; i++){Rblock = this.game.add.sprite(i * Rx,i * Ry,"redBlock"); // x and y are randomy coordinates the ball spawns atthis.game.physics.arcade.enable(Rblock);Rblock.body.velocity.setTo(200,200);Rblock.body.collideWorldBounds = true; Rblock.body.bounce.set(1);} for (var i = 0; i < 3; i++){Bblock = this.game.add.sprite(i * Bx,i * By,"blueBlock"); // x and y are randomy coordinates the ball spawns atthis.game.physics.arcade.enable(Bblock);Bblock.body.velocity.setTo(200,200);Bblock.body.collideWorldBounds = true; Bblock.body.bounce.set(1);} for (var i = 0; i < 3 ; i++){Gblock = this.game.add.sprite(i * Gx,i * Gy,"greenBlock"); // x and y are randomy coordinates the ball spawns atthis.game.physics.arcade.enable(Gblock);Gblock.body.velocity.setTo(200,200);Gblock.body.collideWorldBounds = true; Gblock.body.bounce.set(1);} player = this.game.add.sprite(10,10,"block");this.game.physics.arcade.enable(player);player.anchor.set(0.5);player.body.drag.set(100);player.body.maxVelocity.set(300);//player.scale.setTo(0.2,0.2);player.body.collideWorldBounds = true; game.add.text(16,16,Rx + Ry);game.add.text(16,40,Bx + By);} function update() { if (cursors.up.isDown){this.game.physics.arcade.accelerationFromRotation(player.rotation,200,player.body.acceleration);}else{player.body.acceleration.set(0);}if (cursors.left.isDown){player.body.angularVelocity = -300} else if(cursors.right.isDown){player.body.angularVelocity = 300;}else{player.body.angularVelocity = 0;}}