# U3L25 level 13b -Using a Variable for Random Velocity

We cannot seem to make it run using a Variable to Randomize the velocity of the LadyBug Enemies. The existing Example has it without a Variable too. Anyone use a Variable?

Here’s what we are working with:

// Variables
var score = 0;
var enemy1Speed = randomNumber(1, 4);
var enemy2Speed = randomNumber(1, 4);

// Create Sprites
var cake = createSprite(350,200);
cake.setAnimation(“cake”);

var player = createSprite(200,200);
player.setAnimation(“alienWalkRight”);

var enemy1 = createSprite();
setEnemy1();
enemy1.velocityX = enemy1Speed;

var enemy2 = createSprite();
setEnemy2();
enemy2.velocityX = enemy2Speed;

function draw() {
// draw the background
gameBackground();

// update the sprites
enemiesTouchCake();
movePlayer();
displaceEnemies();
enemiesTouchWater();
showScore();
drawSprites();
}

// Functions
function gameBackground() {
noStroke();
background(rgb(0,100,255));
fill(rgb(100,100,100));
rect(0,150,400,100);
fill(rgb(80,80,80));
rect(0,140,400,10);
rect(0,250,400,10);
}

function enemiesTouchCake(){
if(enemy1.isTouching(cake)){
setEnemy1();
score -= 2;
}

if(enemy2.isTouching(cake)){
setEnemy2();
score -=2;
}
}

function movePlayer(){
if(keyDown(“right”)){
player.setAnimation(“alienWalkRight”);
player.x +=3;
}
if(keyDown(“left”)){
player.setAnimation(“alienWalkLeft”);
player.x -=3;
}
if(keyDown(“up”)){
player.y -=3;
}
if(keyDown(“down”)){
player.y+=3;
}

}

function displaceEnemies(){
player.displace(enemy1);

player.displace(enemy2);

}

function enemiesTouchWater(){
if(enemy1.y < 140){
setEnemy1();
score += 1;
}

if(enemy1.y > 260){
setEnemy1();
score += 1;
}

if(enemy2.y < 140){
setEnemy2();
score += 1;
}

if(enemy2.y > 260){
setEnemy2();
score += 1;
}
}

function showScore() {
fill(“white”);
textSize(20);
text(“Score”,20,20,200,100);
text(score,20,40,200,100);
}

function setEnemy1(){
enemy1.x =0;
enemy1.y = randomNumber(150,250);
enemy1.velocityX = enemy1Speed;

}

function setEnemy2(){
enemy2.x =0;
enemy2.y = randomNumber(150,250);
enemy2.velocityX = enemy2Speed;

}

The code you have provided does randomize the speed. I tested it and turned on a watcher to look at the value of your two variables and each time the game starts, they do generate a random speed and that speed is applied to the velocity.

It may be easier to see if your random speed was between 1 & 10. Then, when it generates a larger speed, you will definitely see the difference.

Check back in if I misunderstood your questions.

Good luck!

Mike