HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Adding an 'enemy' to a game (with randomized properties)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enemywithpropertiesrandomizedaddinggame

Problem

I'm working on a game using the now abandoned Famo.us Javascript framework.

I have the game in a running prototype and I'm building with Cordova and running it on an iPhone 6 using PhoneGap.

There seems to be some performance issues with it and I can't help but notice that a bit of lag happens right as a new enemy is generated onto the field.

There's a few random factors when generating a new enemy:

  • position on the screen



  • type of enemy



  • direction of travel



I think the random factors are slowing the creation down because I'm not very good at high performing code, that said the following works:

```
//speed = velocity (randomly determined before hand - e.g. 300)
//timing = delay until next spawn (also random - e.g. 500)
function addEnemy(speed, timing){
// Famo.us (add node to scenegraph)
var newEnemy = gameEnemies.addChild();
newEnemy.name = "";
newEnemy.num = gameEnemies.iterator++;
// Possible sizes of enemy
var sizes = [30,40,50,60];
// choose a random size
var size = sizes[Math.floor(Math.random()*sizes.length)];
newEnemy.setSizeMode('absolute', 'absolute')
.setAbsoluteSize(size, size);
// possible sides of the screen
var sidesOps = [1,2,3,4];
// choose random side
var sideOp = sidesOps[Math.floor(Math.random()*sidesOps.length)];
// switch through possible sides and place in a random position along that axis and give enemy the name of the side it was placed on
switch (sideOp) {
case 1:
newEnemy.setPosition(gameSize[0],Math.round(Math.random() * gameSize[1]),2);
newEnemy.name = "right";
break;
case 2:
newEnemy.setPosition(-size,Math.round(Math.random() * gameSize[1]),2);
newEnemy.name = "left";
break;
case 3:
newEnemy.setPosition(Math.round(Math.random() * gameSize[0]),gameSize[1],2);
newEnemy.name = "bottom";
break;
case 4:
newEnemy.setPosition(Math.round(Math.random() * gameSize[0]),-size,2);
newEnemy.name = "top";
break;
}
// Famo.us adds D

Solution

I don't think that it is the Math.random() that is causing problems. This jsfiddle calls Math.random() 1 million times in about 60-80 ms (chrome on iPhone 5s). I believe the issue is that you are doing a lot of calculations for each new enemy. There are a couple of ways I can think to avoid this heavy calculation.

You could compute the position (and all the other properties) of your enemies at the beginning of each level, then add the pre-computed enemies when necessary, if you have levels in your game. Another solution could be to introduce "waves" into your game. At the beginning of each wave you could calculate where enemies will spawn.

Context

StackExchange Code Review Q#120250, answer score: 2

Revisions (0)

No revisions yet.