sprite.visible

Category:Sprites

The visibility of the sprite, true or false.

The default visibility is true. All sprite properties can be both accessed and updated.

Examples

Blinking Target

Use sprite.visible to make a target blink.

// Use sprite.visible to make a target blink.
var sprite = createSprite(200, 200);
sprite.setAnimation("target_red1_1");
function draw() {
  background("white");
  if (sprite.visible === true) {
    sprite.visible = false;
  } else {
    sprite.visible = true;
  }
  drawSprites();
}

Peek-A-Boo

Three gnomes playing peek-a-boo, the start of a whack-a-gnome game.

                            // Three gnomes playing peek-a-boo, the start of a whack-a-gnome game.
var up=true, count=1;
var speed=randomNumber(1,10), out=randomNumber(1,3);
var gnome1 = createSprite(100, 200);
var gnome2 = createSprite(200, 200);
var gnome3 = createSprite(300, 200);
setUp();
function draw() {
  background("white");
  setOneGnomeVisible();
  count = count + 1;
  if (count>=randomNumber(20,28)) changeGnomesDirection();
  moveGnomes();
  drawSprites();
  rect(0, 200, 400, 200);  
}
function setUp() {
  gnome1.setAnimation("gnome_1");
  gnome2.setAnimation("gnome_1");
  gnome3.setAnimation("gnome_1");
  gnome1.visible=false;
  gnome2.visible=false;
  gnome3.visible=false;
  drawSprites();
  rect(0, 200, 400, 200);
}
function setOneGnomeVisible() {
  if (out==1) {
    gnome1.visible=true;
  }
  else if (out==2) {
    gnome2.visible=true;
  }    
  else {
    gnome3.visible=true;
  }  
}
function changeGnomesDirection() {
  count=0;
  speed=randomNumber(3,6);
  if (up) {
    up=false;
    gnome1.visible=false;
    gnome2.visible=false;
    gnome3.visible=false;
    gnome1.y=300;
    gnome2.y=300;
    gnome3.y=300;      
    out=randomNumber(1,3);    
  }
  else {
    up=true;
  }
}
function moveGnomes() {
  if (up) {
    gnome1.y=gnome1.y+speed;
    gnome2.y=gnome2.y+speed;
    gnome3.y=gnome3.y+speed;
  }
  else {
    gnome1.y=gnome1.y-speed;
    gnome2.y=gnome2.y-speed;
    gnome3.y=gnome3.y-speed;
  }
}
                        

var sprite = createSprite(200, 200);
sprite.visible = false;
drawSprites();

Syntax

sprite.visible

Returns

Boolean true or false.

Tips

  • Sprites all have the same properties and you use the dot notation (combining the name of the sprite, followed by a dot, with the label of the property) to both access and update the property for that sprite.
  • Any changes to the properties of a sprite will not be seen until after drawSprites() is called.
  • A sprite that is not visible can still collide with other sprites and user mouse interactions.

Found a bug in the documentation? Let us know at documentation@code.org