Jump to content

Spawning sprites randomly for endless runner


laduree77
 Share

Recommended Posts

I have an idea of how I want to spawn obstacles for my endless runner game; what I want to do is spawn them randomly on the right and move them towards the left hand side of the screen. And once they are out of bounds of the screen, I want to kill them. But I need some help figuring out how to write the function that would do this. So far I've made a title screen, and the basic "treadmill" structure of the endless runner with player movement.

 

var game = new Phaser.Game(820, 360, Phaser.AUTO);

var mainMenu = function(game) {};
mainMenu.prototype = {
	preload: function() {
		//preloading assets
		game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		// background
    		this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
   		this.background.autoScroll(-100, 0);

    		// ground
    		this.background = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
    		this.background.autoScroll(-200, 0);

    		// player
    		this.player = this.add.sprite(30, 253, 'sprites', 'bunny');
    		this.player.animations.add('run', Phaser.Animation.generateFrameNames('bunny', 4, 5, "", 4), 10, true);
    		this.player.animations.play('run', 10, true);

    		// logo
    		this.splash = this.add.sprite(this.game.world.centerX, this.game.world.centerY - 40, 'sprites', 'logo');
    		this.splash.anchor.setTo(0.5);
  	},
  	update: function () {
    		if (this.game.input.activePointer.justPressed()) {
      			this.game.state.start('gamePlay');
    		}
  	}
};

var gamePlay = function(game) {};
gamePlay.prototype = {
	preload: function() {
		//preloading assets
		game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		// physics engine
    		this.game.physics.startSystem(Phaser.Physics.ARCADE);
    		this.game.physics.arcade.gravity.y = 2000;

		// background
    		this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
    		this.background.autoScroll(-100, 0);

	    	// ground
    		this.ground = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
    		this.ground.autoScroll(-200, 0);

		// player
    		this.player = this.add.sprite(30, 253, 'sprites', 'bunny');
    		this.player.animations.add('right', Phaser.Animation.generateFrameNames('bunny', 4, 5, '', 4), 10, true);
    		this.player.animations.play('right', 10, true);
		
		// 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;
	
		//add spacebar for jump
		this.jumpButton = this.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
 	},
  	update: function () {
    		// look for collisions between sprites
    		this.game.physics.arcade.collide(this.player, this.ground);

		//add arrow keys for movement
		var cursors = this.input.keyboard.createCursorKeys();

		//reset player velocity
		this.player.body.velocity.x = 0;

		//moving right
		if (cursors.right.isDown) {
			this.player.body.velocity.x = 90;
			this.player.animations.play('right');
		}
		else if (cursors.left.isDown) {
			this.player.body.velocity.x = -90;
			this.player.animations.play('right');
		}

    		// jump
    		if (this.jumpButton.isDown && (this.player.body.touching.down)) {
      			this.player.body.velocity.y = -800;
    		}
  	}
};

var gameOver = function(game) {};

gameOver.prototype = {
	preload: function() {
		//preloading assets
		game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		console.log('create');
		game.stage.backgroundColor = '#4488AA';

		//click to start text
    this.game.add.text(this.game.world.centerX - 100, this.game.world.centerY + 80, 'Click to return to main menu', { font: "30px Raleway"} );

  	},
  	update: function () {
    		if (this.game.input.activePointer.justPressed()) {
      			this.game.state.start('mainMenu');
    		}
  	}
}

game.state.add('mainMenu', mainMenu);
game.state.add('gamePlay', gamePlay);
game.state.add('gameOver', gameOver);
game.state.start('mainMenu');



 

sprites.json

spritesheet.png

Link to comment
Share on other sites

Start with a timer function and an array that stores your obstacles in the UPDATE cycle.

Quote

 

do this each second {

    arrayForObstacles.push(

        this.game.add.sprite( x, y, 'obstacle')

        // Also some collision code is needed here

    )

}

 

And with this we've created an obstacle generator. You can also add Phaser.Math.random(0,64) to x and/or y position of an obstacle for randomness

Next we need to manage the obstacles
 

Quote

 

for ( var i = 0; i < arrayForObstacles.length; i++ ) {

    arrayForObstacles.x -= 5; // Move obstacle to the left

    if ( arrayForObstacles.x <= 0 ) {

        arrayForObstacles.kill() //remove from the game

        arrayForObstacles.splice(i,1) // remove from array

    }

}

 

I bet phaser group collision can do a better job here though but you'll have to read up on it yourself, because I don't know much about it. Hope it helps.

 

Link to comment
Share on other sites

@Mickety Thanks again! I've finally found a way to spawn obstacles randomly, but they seem to be falling through the ground. I've double checked and I did check for collision between the right things, but it's still falling through. :( Any help would be appreciated!!

var game = new Phaser.Game(820, 360, Phaser.AUTO);

var mainMenu = function(game) {};
mainMenu.prototype = {
	preload: function() {
		//preloading assets
		this.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		// background
    		this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
   		this.background.autoScroll(-100, 0);

    		// ground
    		this.background = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
    		this.background.autoScroll(-200, 0);

    		// player
    		this.player = this.add.sprite(30, 253, 'sprites', 'bunny');
    		this.player.animations.add('run', Phaser.Animation.generateFrameNames('bunny', 4, 5, "", 4), 10, true);
    		this.player.animations.play('run', 10, true);

    		// logo
    		this.splash = this.add.sprite(this.game.world.centerX, this.game.world.centerY - 40, 'sprites', 'logo');
    		this.splash.anchor.setTo(0.5);
  	},
  	update: function () {
    		if (this.game.input.activePointer.justPressed()) {
      			this.game.state.start('gamePlay');
    		}
  	}
};

var obstacle;
var timer = 0;

var gamePlay = function(game) {};
gamePlay.prototype = {
	preload: function() {
		//preloading assets
		game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		// physics engine
    		this.game.physics.startSystem(Phaser.Physics.ARCADE);
    		this.game.physics.arcade.gravity.y = 2000;

		// background
    		this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
    		this.background.autoScroll(-100, 0);

	    	// ground
    		this.ground = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
    		this.ground.autoScroll(-300, 0);

		// player
    		this.player = this.add.sprite(30, 253, 'sprites', 'bunny');
    		this.player.animations.add('right', Phaser.Animation.generateFrameNames('bunny', 4, 5, '', 4), 10, true);
    		this.player.animations.play('right', 10, true);

		// physics on sprites
    		this.physics.arcade.enable([this.player, this.ground]);
    		this.ground.body.immovable = true;
    		this.ground.body.allowGravity = false;
    		this.player.body.collideWorldBounds = true;

		//give player slight bounce
		this.player.body.bounce.y = 0.5;
		this.player.body.gravity.y = 200;
		this.player.body.collideWorldBounds = true;

		//create group for obstacles
		obstacle = this.add.group();
		obstacle.enableBody = true;

		//create the hill obstacle
		//var hill = obstacle.create(((Math.random() * 800) + 550), (Math.random() * 700), 'sprites', 'obstacle');
		//hill.body.gravity.y = 0;

		//spawn obstacles
		this.makeObstacles();
	},

 	makeObstacles: function () {
		for (var i = 0; i < ((Math.random() * 3) + 1); i++) {
			var hill = obstacle.create(((Math.random() * 900) + 800), ((Math.random() * 500) + 20), 'sprites', 'obstacle');
			//hill.body.immovable = true;
			//hill.scale.x *= -1;
			hill.body.gravity.y = 6;
			hill.body.velocity.x = ((Math.random() * -200) - 100);
		}
	},

  	update: function () {
  		//spawn more hills
  		if(timer % 300 == 0) {
  			this.makeObstacles();
  		}

  		//look for collisions between hill and ground
  		this.physics.arcade.collide(this.obstacle, this.ground);

    	//look for collisions between sprites
    	this.physics.arcade.collide(this.player, this.ground);

		//add arrow keys for movement
		var cursors = this.input.keyboard.createCursorKeys();

		//reset player velocity
		this.player.body.velocity.x = 0;

		//moving player
    		if (cursors.up.isDown && (this.player.body.touching.down)) {
      			this.player.body.velocity.y = -850;
    		}
		else if (cursors.right.isDown) {
			this.player.body.velocity.x = 60;
			this.player.animations.play('right');
		}
		else if (cursors.left.isDown) {
			this.player.body.velocity.x = -90;
			this.player.animations.play('right');
		}
  	}
};

var gameOver = function(game) {};

gameOver.prototype = {
	preload: function() {
		//preloading assets
		game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		console.log('create');
		game.stage.backgroundColor = '#4488AA';

		//click to start text
    this.game.add.text(this.game.world.centerX - 100, this.game.world.centerY + 80, 'Click to return to main menu', { font: "30px Raleway"} );

  	},
  	update: function () {
    		if (this.game.input.activePointer.justPressed()) {
      			this.game.state.start('mainMenu');
    		}
  	}
}

game.state.add('mainMenu', mainMenu);
game.state.add('gamePlay', gamePlay);
game.state.add('gameOver', gameOver);
game.state.start('mainMenu');



 

Link to comment
Share on other sites

Hi @laduree77 ,

Some points that I think can help you to optimize your code:

1) In your current code you are continuously creating elements of the "obstacle" group, which causes a significant drop in the fps.
The best option in your case is to recycle the obstacles when they leave the screen.
2) For collisions with the ground you can redefine the world bounds and use bottom bound as a floor.
3) When you load an asset of the game, it does not disappear when changing to another state. Here you only need the first preload().
4) The creation of objects or variables that are not going to change is better done in the create () method, since it only runs one time. This is the case of "cursors". 

Here a possible solution to your problem of collisions with the ground and the fall of the fps:


var game = new Phaser.Game(820, 360, Phaser.AUTO);

var mainMenu = function(game) {};
mainMenu.prototype = {
	preload: function() {
		//preloading assets
		this.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		// background
    		this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
   		this.background.autoScroll(-100, 0);

    		// ground
    		this.background = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
    		this.background.autoScroll(-200, 0);

    		// player
    		this.player = this.add.sprite(30, 253, 'sprites', 'bunny0000');
    		this.player.animations.add('run', Phaser.Animation.generateFrameNames('bunny', 4, 5, "", 4), 10, true);
    		this.player.animations.play('run', 10, true);

    		// logo
    		this.splash = this.add.sprite(this.game.world.centerX, this.game.world.centerY - 40, 'sprites', 'logo');
    		this.splash.anchor.setTo(0.5);
  	},
  	update: function () {
    		if (this.game.input.activePointer.justPressed()) {
      			this.game.state.start('gamePlay');
    		}
  	}
};

var obstacle;

var gamePlay = function(game) {};
gamePlay.prototype = {
 
 	create: function () {
		//world bounds rectangle ********************************************************
			game.world.bounds.x = -100;
			game.world.bounds.width = game.width + 100 + (1700-820); 
			game.world.bounds.height = game.height-50;

		// physics engine
    		game.physics.startSystem(Phaser.Physics.ARCADE);

		// background
    		this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
    		this.background.autoScroll(-100, 0);

	    	// ground
    		this.ground = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
    		this.ground.autoScroll(-300, 0);

		// player
    		this.player = this.add.sprite(30, 253, 'sprites', 'bunny0000');
    		this.player.animations.add('right', Phaser.Animation.generateFrameNames('bunny', 4, 5, '', 4), 10, true);
    		this.player.animations.play('right', 10, true);

		// physics on sprites
    		game.physics.arcade.enable([this.player, this.ground]);
    		this.ground.body.immovable = true;
    		this.ground.body.allowGravity = false;

		//give player slight bounce
		this.player.body.bounce.y = 0.2;
		this.player.body.gravity.y = 1000;
		this.player.body.collideWorldBounds = true;

		//create group for obstacles
		obstacle = this.add.group();
		obstacle.enableBody = true;
		obstacle.physicsBodyType=Phaser.Physics.ARCADE;

		//spawn obstacles
		this.makeObstacles(4);
	},

 	makeObstacles: function (numberOfHills) {
		for (var i = 0; i < numberOfHills; i++) {
			var hill = obstacle.create(((Math.random() * 900) + 800), ((Math.random() * 250) -20), 'sprites', 'obstacle');
			//hill.body.immovable = true;
			//hill.scale.x *= -1;
			hill.body.gravity.y = 200;
			hill.body.velocity.x = ((Math.random() * -200) - 100);
			hill.body.collideWorldBounds = true;
		}
	},

  	update: function () {
		  
		//look for hills out of screen to recycle
  		obstacle.forEach(function(item){
			  if(item.x < -60){
				  item.reset(((Math.random() * 900) + 750), ((Math.random() * 250) - 20));
				  item.body.gravity.y = 200;
				  item.body.velocity.x = ((Math.random() * -200) - 100);
				  item.body.collideWorldBounds = true;
			  }
		  })

  		 	

		//add arrow keys for movement
		var cursors = this.input.keyboard.createCursorKeys();

		//reset player velocity
		this.player.body.velocity.x = 0;

		//moving player
    		if (cursors.up.isDown && this.player.body.onFloor()) {
      			this.player.body.velocity.y = -850;
    		}
		else if (cursors.right.isDown) {
			this.player.body.velocity.x = 60;
			this.player.animations.play('right');
		}
		else if (cursors.left.isDown) {
			this.player.body.velocity.x = -90;
			this.player.animations.play('right');
		}
	  }
};

var gameOver = function(game) {};

gameOver.prototype = {
 
 	create: function () {
		console.log('create');
		game.stage.backgroundColor = '#4488AA';

		//click to start text
    this.game.add.text(this.game.world.centerX - 100, this.game.world.centerY + 80, 'Click to return to main menu', { font: "30px Raleway"} );

  	},
  	update: function () {
    		if (this.game.input.activePointer.justPressed()) {
      			this.game.state.start('mainMenu');
    		}
  	}
}

game.state.add('mainMenu', mainMenu);
game.state.add('gamePlay', gamePlay);
game.state.add('gameOver', gameOver);
game.state.start('mainMenu');

Greetings and good luck!!

Link to comment
Share on other sites

@onlycape Wow! Thank you so much for the detailed explanation! I also noticed the drop in FPS as I was testing it aha. I gave your solution a try, but the obstacles still seem to be falling through the ground :( However, the FPS does seem to be better than before! I'll post my code below:

var game = new Phaser.Game(820, 360, Phaser.AUTO);

var mainMenu = function(game) {};
mainMenu.prototype = {
	preload: function() {
		//preloading assets
		this.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		// background
    		this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
   		this.background.autoScroll(-100, 0);

    		// ground
    		this.background = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
    		this.background.autoScroll(-400, 0);

    		// player
    		this.player = this.add.sprite(30, 253, 'sprites', 'bunny');
    		this.player.animations.add('run', Phaser.Animation.generateFrameNames('bunny', 4, 5, "", 4), 10, true);
    		this.player.animations.play('run', 10, true);

    		// logo
    		this.splash = this.add.sprite(this.game.world.centerX, this.game.world.centerY - 40, 'sprites', 'logo');
    		this.splash.anchor.setTo(0.5);
  	},
  	update: function () {
    		if (this.game.input.activePointer.justPressed()) {
      			this.game.state.start('gamePlay');
    		}
  	}
};

var obstacle;
var timer = 0;
var score = 0;
var scoreText;

var gamePlay = function(game) {};
gamePlay.prototype = {
	preload: function() {
		//preloading assets
		game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
 		//making a world bounds rectangle
 		this.world.bounds.x = -100;
 		this.world.bounds.width = game.width + 100 + (1700 - 820);
 		this.world.bounds.height = this.height - 50;

		// physics engine
    		this.physics.startSystem(Phaser.Physics.ARCADE);
    		//this.physics.arcade.gravity.y = 2000;

		// background
    		this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
    		this.background.autoScroll(-100, 0);

	    	// ground
    		this.ground = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
    		this.ground.autoScroll(-400, 0);

		// player
    		this.player = this.add.sprite(30, 253, 'sprites', 'bunny');
    		this.player.animations.add('right', Phaser.Animation.generateFrameNames('bunny', 4, 5, '', 4), 10, true);
    		this.player.animations.play('right', 10, true);

		// physics on sprites
    		this.physics.arcade.enable([this.player, this.ground]);
    		this.ground.body.immovable = true;
    		this.ground.body.allowGravity = false;
    		//this.player.body.collideWorldBounds = true;

		//give player slight bounce
		this.player.body.bounce.y = 0.2;
		this.player.body.gravity.y = 1000;
		this.player.body.collideWorldBounds = true;

		//create group for obstacles
		obstacle = this.add.group();
		obstacle.enableBody = true;
		obstacle.physicsBodyType = Phaser.Physics.ARCADE;

		//create the hill obstacle
		//var hill = obstacle.create(((Math.random() * 800) + 550), (Math.random() * 700), 'sprites', 'obstacle');
		//hill.body.gravity.y = 0;

		//displays score text on screen
		scoreText = game.add.text(16, 16, 'Score: 0', {fontSize: '32px', fill: '#FFFFFF'});

		//spawn obstacles
		this.makeObstacles(4);
	},

	makeObstacles: function (numberOfHills) {
		for (var i = 0; i < numberOfHills; i++) {
			var hill = obstacle.create(((Math.random() * 900) + 800), ((Math.random() * 250) - 20), 'sprites', 'obstacle');
			hill.body.gravity.y = 200;
			hill.body.velocity.x = ((Math.random() * -200) - 100);
			hill.body.collideWorldBounds = true;
		}
	},
 	//makeObstacles: function () {
		//for (var i = 0; i < ((Math.random() * 3) + 1); i++) {
			//var hill = obstacle.create(((Math.random() * 900) + 800), ((Math.random() * 500) + 20), 'sprites', 'obstacle');
			//var hill = obstacle.create(((Math.random() * 900) + 800), 230, 'sprites', 'obstacle');
			//hill.body.immovable = true;
			//hill.scale.x *= -1;
			//hill.body.gravity.y = 0;
			//hill.body.velocity.x = ((Math.random() * -200) - 100);
		//}
	//},

  	update: function () {
  		//look for hills off screen to recycle
  		obstacle.forEach(function(item) {
  			if (item.x < -60) {
  				item.reset(((Math.random() * 900) + 750), ((Math.random() * 250) - 20));
  				item.body.gravity.y = 200;
  				item.body.velocity.x = ((Math.random() * -200) - 100);
  				item.body.collideWorldBounds = true;
  			}
  		})

  		//spawn more hills
  		if (timer % 100 == 0) {
  			this.makeObstacles();
  		}

  		if (timer % 1000 == 0) {
  			score += 1;
  			scoreText.text = 'Score: ' + score;
  		}

    	//look for collisions between sprites
    	this.physics.arcade.collide(this.player, this.ground);

		//add arrow keys for movement
		var cursors = this.input.keyboard.createCursorKeys();

		//reset player velocity
		this.player.body.velocity.x = 0;

		//moving player
    		if (cursors.up.isDown && (this.player.body.touching.down)) {
      			this.player.body.velocity.y = -850;
    		}
		else if (cursors.right.isDown) {
			this.player.body.velocity.x = 60;
			this.player.animations.play('right');
		}
		else if (cursors.left.isDown) {
			this.player.body.velocity.x = -90;
			this.player.animations.play('right');
		}
  	}
};

var gameOver = function(game) {};

gameOver.prototype = {
	preload: function() {
		//preloading assets
		game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
	},
 
 	create: function () {
		console.log('create');
		game.stage.backgroundColor = '#4488AA';

		//click to start text
    this.game.add.text(this.game.world.centerX - 100, this.game.world.centerY + 80, 'Click to return to main menu', { font: "30px Raleway"} );

  	},
  	update: function () {
    		if (this.game.input.activePointer.justPressed()) {
      			this.game.state.start('mainMenu');
    		}
  	}
}

game.state.add('mainMenu', mainMenu);
game.state.add('gamePlay', gamePlay);
game.state.add('gameOver', gameOver);
game.state.start('mainMenu');


 

Link to comment
Share on other sites

Hi @laduree77,

I have tested the code I showed you before and it works for me (Phaser 2.10.1).

Here is the problem in your new code:

this.world.bounds.height = this.height - 50;

"this.height" is undefined. You have to use "this.game.height" or "game.height". 

After that, you don't need apply physics to the ground. 

Right now, the call to makeObstacles in the update method isn't doing anything because it needs a parameter (number of obstacles to generate). But if you generate obstacles in the update () (it is executed 30/60 times per second), you must implement a method to destroy the obstacles that you don't need or in a few seconds you will have thousands, with which you will have performance problems and the game will be unplayable.
The main idea of the code that I showed you is the reuse of the obstacles (I created 4, but obviously you can put the ones you want) to avoid to collapse the resources and the creation of new objects (slower than reusing existing ones).

Greetings.

 

Link to comment
Share on other sites

@laduree77 Upsss, I think it's my fault :rolleyes:.

The problem is that the initial "Y" coordinate of some obstacles is outside the world bounds and I imagine that it can produce that behavior.

In this expression:

((Math.random() * 250) - 20)

change "-20" with any positive value. Tell me if that solves the problem.

PS: You should post a new thread for a new problem, because that way you'll find help more easily and help other people with the same problem. 

Link to comment
Share on other sites

@onlycape Ah, looks like it's still happening! :( I can't quite tell, but either the hills aren't moving or they're moving towards the right :o And @Mickety it still happens with Phaser.Math.random() too :( Here's my code so far:

var game = new Phaser.Game(820, 360, Phaser.AUTO);

var mainMenu = function(game) {};
mainMenu.prototype = {
  preload: function() {
    //preloading assets
    this.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
  },
 
  create: function () {
    // background
      this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
      this.background.autoScroll(-100, 0);

        // ground
        this.background = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
        this.background.autoScroll(-400, 0);

        // player
        this.player = this.add.sprite(30, 253, 'sprites', 'bunny');
        this.player.animations.add('run', Phaser.Animation.generateFrameNames('bunny', 4, 5, "", 4), 10, true);
        this.player.animations.play('run', 10, true);

        // logo
        this.splash = this.add.sprite(this.game.world.centerX, this.game.world.centerY - 40, 'sprites', 'logo');
        this.splash.anchor.setTo(0.5);
    },
    update: function () {
        if (this.game.input.activePointer.justPressed()) {
            this.game.state.start('gamePlay');
        }
    }
};

var obstacle;
var timer = 0;
var score = 0;
var scoreText;

var gamePlay = function(game) {};
gamePlay.prototype = {
  preload: function() {
    //preloading assets
    game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
  },
 
  create: function () {
    //making a world bounds rectangle
    this.world.bounds.x = -100;
    this.world.bounds.width = game.width + 100 + (1700 - 820);
    this.world.bounds.height = this.game.height - 50;

    // physics engine
        this.physics.startSystem(Phaser.Physics.ARCADE);
        //this.physics.arcade.gravity.y = 2000;

    // background
        this.background = this.game.add.tileSprite(0, -30, this.game.width, 390, 'sprites', 'background');
        this.background.autoScroll(-100, 0);

        // ground
        this.ground = this.game.add.tileSprite(0, 310, this.game.width, 60, 'sprites', 'ground');
        this.ground.autoScroll(-400, 0);

    // player
        this.player = this.add.sprite(30, 253, 'sprites', 'bunny');
        this.player.animations.add('right', Phaser.Animation.generateFrameNames('bunny', 4, 5, '', 4), 10, true);
        this.player.animations.play('right', 10, true);

    // physics on sprites
        this.physics.arcade.enable([this.player, this.ground]);
        this.ground.body.immovable = true;
        this.ground.body.allowGravity = false;
        //this.player.body.collideWorldBounds = true;

    //give player slight bounce
    this.player.body.bounce.y = 0.2;
    this.player.body.gravity.y = 1000;
    this.player.body.collideWorldBounds = true;

    //create group for obstacles
    obstacle = this.add.group();
    obstacle.enableBody = true;
    obstacle.physicsBodyType = Phaser.Physics.ARCADE;

    //displays score text on screen
    scoreText = game.add.text(16, 16, 'Score: 0', {fontSize: '32px', fill: '#FFFFFF'});

    //spawn obstacles
    this.makeObstacles(4);
  },

  makeObstacles: function (numberOfHills) {
    for (var i = 0; i < numberOfHills; i++) {
      var hill = obstacle.create(((Math.random() * 900) + 800), ((Math.random() * 250) + 50), 'sprites', 'obstacle');
      hill.body.gravity.y = 200;
      hill.body.velocity.x = ((Math.random() * -200) - 100);
      hill.body.collideWorldBounds = true;
    }
  },

    update: function () {
      //look for hills off screen to recycle
      obstacle.forEach(function(item) {
        if (item.x < -60) {
          item.reset(((Math.random() * 900) + 750), ((Math.random() * 250) + 50));
          item.body.gravity.y = 200;
          item.body.velocity.x = ((Math.random() * -200) - 100);
          item.body.collideWorldBounds = true;
        }
      })

      if (timer % 1000 == 0) {
        score += 1;
        scoreText.text = 'Score: ' + score;
      }

      //look for collisions between sprites
      this.physics.arcade.collide(this.player, this.ground);

    //add arrow keys for movement
    var cursors = this.input.keyboard.createCursorKeys();

    //reset player velocity
    this.player.body.velocity.x = 0;

    //moving player
        if (cursors.up.isDown && (this.player.body.onFloor())) {
            this.player.body.velocity.y = -650;
        }
    else if (cursors.right.isDown) {
      this.player.body.velocity.x = 60;
      this.player.animations.play('right');
    }
    else if (cursors.left.isDown) {
      this.player.body.velocity.x = -90;
      this.player.animations.play('right');
    }
    }
};

var gameOver = function(game) {};

gameOver.prototype = {
  preload: function() {
    //preloading assets
    game.load.atlas('sprites', 'assets/img/spritesheet.png', 'assets/img/sprites.json');
  },
 
  create: function () {
    console.log('create');
    game.stage.backgroundColor = '#4488AA';

    //click to start text
    this.game.add.text(this.game.world.centerX - 100, this.game.world.centerY + 80, 'Click to return to main menu', { font: "30px Raleway"} );

    },
    update: function () {
        if (this.game.input.activePointer.justPressed()) {
            this.game.state.start('mainMenu');
        }
    }
}

game.state.add('mainMenu', mainMenu);
game.state.add('gamePlay', gamePlay);
game.state.add('gameOver', gameOver);
game.state.start('mainMenu');

Link to comment
Share on other sites

@laduree77 Don't worry :D, the problem remains the same.

Knowing the upper left corner (-100 , 0) and the lower right corner (1700 , 310) of the rectangle of the world bounds and the width and height of the obstacles (70x70), the possible coordinates of these will be:

-100 < obstacle.x < 1630

0 < obstacle.y < 240

In the code some obstacles are generated outside these limits.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...