Student gets Overlap error with the following code

// Create your variables here
var score = 0;
var chick_1 = createSprite(20, 300);
chick_1.setAnimation(“chick_1”);
chick_1.scale = 0.2;
var car_red_1 = createSprite(156, 440);
car_red_1.velocityY = -3;
car_red_1.setAnimation(“car_red_1”);
car_red_1.displace(car_yellow_1);
var motorcycle_1 = createSprite(156, 700);
motorcycle_1.setAnimation(“motorcycle_1”);
motorcycle_1.velocityY = -3.3;
motorcycle_1.displace(car_red_1);
var car_green_1 = createSprite(234, 850);
car_green_1.setAnimation(“car_green_1”);
car_green_1.velocityY = -1.9;
var car_yellow_1 = createSprite(156, 960);
car_yellow_1.setAnimation(“car_yellow_1”);
car_yellow_1.velocityY = -3;
car_yellow_1.displace(motorcycle_1);

// Create your sprites here

function draw() {
// draw background
road();
stripe();

// update sprites
if (car_red_1.y < -250) {
car_red_1.y = 560;
}
if (car_black_1.y < -250) {
car_black_1.y = 700;
}
if (motorcycle_1.y < -250) {
motorcycle_1.y = 820;
}
if (car_green_1.y < -250) {
car_green_1.y = 970;
}
if (car_yellow_1.y < -250) {
car_yellow_1.y = 1080;
}

drawSprites();
showScore();
}

// Create your functions here
function road() {
background(“green”);
rect(125, 0, 150, 40000);
fill(“grey”);
}
function stripe() {
rect(192, 0, 12, 4000);
fill(“yellow”);
}
function showScore() {
fill(“black”);
textSize(15);
text("Score: ", 0, 15);
text(score, 60, 15);
}

It says that the error is caused here: motorcycle_1.setAnimation(“motorcycle_1”);

Hi,

The issue has to do with the order in which the student is declaring/referencing the variables. When the code says, for example, car_red_1.displace(car_yellow_1);, there’s an error because car_yellow_1 doesn’t actually exist until it’s declared a few lines later. So the code is checking for overlap (in order to do the displace) between a sprite and a nonexistent object.

Try creating all the variables and setting the animations first, e.g.

var car_yellow_1 = createSprite(156, 960);
car_yellow_1.setAnimation("car_yellow_1");

var car_red_1 = createSprite(156, 440);
car_red_1.setAnimation("car_red_1");

var motorcycle_1 = createSprite(156, 700);
motorcycle_1.setAnimation("motorcycle_1");

And then doing the velocity/displace code for each sprite.

Best,
Laurence

1 Like