Sprite visible behavior

A student had problems where there were two sprites and after touching one of them is set to true and the other to false. When the reverse happens the code does not make the change.
In my sample it starts off with the dog moving towards a flute(obstacle), and it changes to the cat when it touches the flute, but the cat never changes back to the dog. It never gets to the “in touching cat” part of the code.

var cat = createSprite(0, 200);
cat.setAnimation(“cat”);
cat.velocityX = 2;
var dog = createSprite(0, 200);
dog.setAnimation(“dog”);
dog.velocityX = 2;
var flute = createSprite(200, 200);
flute.setAnimation(“flute”);

cat.scale = .3;
dog.scale = .2;
flute.scale = .5;
cat.visible = false ;

function draw(){
background(“white”);

if(dog.isTouching(flute)){
dog.x = dog.x + 20;
cat.x = dog.x
dog.visible = false;
cat.visible = true;
console.log(“in dog touching”);
}

if(cat.isTouching(flute)){
cat.x = cat.x + 20;
dog.x = cat.x;
cat.visible = false;
dog.visible = true;
console.log(“in cat touching”);
}

if(cat.x > 400)
cat.x = 0;
if(dog.x > 400)
dog.x = 0;

drawSprites();
}

I’m not sure that this will fix the issues but it has worked for a lot of my students.
Both of the touching conditionals are separate if statements. That means that the both can be true for each time through the draw loop. Since they are basically reversing the visibility of the the cat and dog sprite, it may look like nothing is happening but it may be that they are both happening. You can check this by looking at the console to see if the “in dog touching” messages are being printed.

I’d suggest making the two if statements into an if / else if statement to see how that works.
Let us know how it works

My initial response to the student was to try the if else and it did not work. I look at it further and figured out that one needs to check the isTouching and visible at the same time, as shown below.

if(dog.isTouching(flute) && dog.visible == true){
dog.x = dog.x + 20;
cat.x = dog.x
dog.visible = false;
cat.visible = true;
console.log(“in dog touching”);
console.log("------------------- “);
} else if(cat.isTouching(flute) && cat.visible == true){
cat.x = cat.x + 20;
dog.x = cat.x;
cat.visible = false;
dog.visible = true;
console.log(“in cat touching”);
console.log(”++++++++++++++++");
}

Yeah, that makes sense. It only should work for the cat if it is visible. Nice work.