Jump to content

Change a crated image


iamnotanumber10
 Share

Recommended Posts

Hi, I have some random images that run across the x axis. When they go out of bounds, I pass them to a function that randomly re-positions them on the y axis again. 

xAxisEnemy.reset(negatedEnemyWidth, newPositionY);

Which works fine (on the y axis). However, I'm trying to change the image after it was created in the earlier function. 

xAxisEnemy = enemy.create(negatedEnemyWidth, (i * 120) + 15, randomxAxisEnemy.toString());

I thought I could do something like 

xAxisEnemy.key = randomxAxisEnemy.toString();

would do it before the reset, but it didn't work out like that. 

Any ideas?

Here is the code for the 2 functions. 

Thanks :)

function createEnemy(){
	skipEnemy = Math.floor(Math.random() * 4);
	for (var i = 0; i < 4; i++) {
		if(i != skipEnemy) {
			var randomSpeed = Math.floor((Math.random() * 50) + 30); // 30 - 80
			var randomxAxisEnemy = xAxisEnemyAssets[Math.floor(Math.random() * xAxisEnemyAssets.length)];
			var negatedEnemyWidth = -Math.abs(game.cache.getImage(randomxAxisEnemy).width);

			xAxisEnemy = enemy.create(negatedEnemyWidth, (i * 120) + 15, randomxAxisEnemy.toString());
			xAxisEnemy.checkWorldBounds = true;
			xAxisEnemy.events.onOutOfBounds.add(xAxisEnemyRespawn, this);
			xAxisEnemy.body.gravity.y = 0;
			xAxisEnemy.body.velocity.x = randomSpeed;
		}
	}
}

// respawn after going out of bounds
function xAxisEnemyRespawn(xAxisEnemy) {
	var newPositionY = (Math.floor(Math.random() * 4) * 120) + 15;
	var randomxAxisEnemy = xAxisEnemyAssets[Math.floor(Math.random() * xAxisEnemyAssets.length)];
	xAxisEnemy.key = randomxAxisEnemy.toString();

	var negatedEnemyWidth = -Math.abs(game.cache.getImage(xAxisEnemy.key).width);
	xAxisEnemy.reset(negatedEnemyWidth, newPositionY);
	xAxisEnemy.body.velocity.x = Math.floor((Math.random() * 50) + 30);
}

 

Link to comment
Share on other sites

Oh hi, I just did it another way...

function create() {

...
  
	if (enemy.length < 4) {
		for (var i = 0; i < 3; i++) {
			createEnemy();
		}
	}
}

function createEnemy(){
	var randomPosition = Math.floor(Math.random() * 4);
	var randomSpeed = Math.floor((Math.random() * 50) + 30); // 30 - 80
	var randomxAxisEnemy = xAxisEnemyAssets[Math.floor(Math.random() * xAxisEnemyAssets.length)];
	var negatedEnemyWidth = -Math.abs(game.cache.getImage(randomxAxisEnemy).width);

	xAxisEnemy = enemy.create(negatedEnemyWidth, (randomPosition * 120) + 15, randomxAxisEnemy.toString());
	xAxisEnemy.checkWorldBounds = true;
	xAxisEnemy.events.onOutOfBounds.add(xAxisEnemyRespawn, this);
	xAxisEnemy.body.gravity.y = 0;
		xAxisEnemy.body.velocity.x = randomSpeed;
}

// respawn after going out of bounds
function xAxisEnemyRespawn(xAxisEnemy) {
	xAxisEnemy.kill(); // remove the enemy
	createEnemy(); // create a new enemy
}

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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