camera.on()

Category:Game Lab

Activates the camera. The display area will be drawn according to the camera position and scale until camera.off() is called.

The camera enables scrolling and zooming for scenes extending beyond the display area. A camera has a position, a zoom factor, and mouse coordinates relative to the view. The camera is automatically created and available for use.

Examples

Hold the mouse down to activate the camera and link to the sprite movement.

// Hold the mouse down to activate the camera and link to the sprite movement.
var back = createSprite(200, 200);
back.setAnimation("stone_snow_1");
back.scale = 3;
var sprite = createSprite(200,200);
sprite.setAnimation("ladybug_1");

function draw() {
  background("white");
  drawSprites();
  if (keyDown("right")) {
    sprite.x = sprite.x+5;
  }
  if (keyDown("left")) {
    sprite.x = sprite.x-5;
  }
  if (mouseDown("leftButton")) {
    camera.on();
    camera.x=sprite.x;
    camera.y=sprite.y;    
  }
  else {
      camera.off();
  }
}

Follow the Alien

Link the camera to the main sprite movement and scroll stationary sprites.

                            // Link the camera to the main sprite movement and scroll stationary sprites.
var sprite = createSprite(200,200);
sprite.setAnimation("alienBlue_walk_1");
var cactus = createSprite(100, 300);
var fence = createSprite(300, 300);
cactus.setAnimation("cactus_1");
fence.setAnimation("fence_wood_1");
camera.on();
function draw() {
  background("white");
  drawSprites();
  camera.x=sprite.x;
  camera.y=sprite.y;
  if (keyDown("right")) {
    sprite.x = sprite.x+5;
    sprite.mirrorX(1);
  }
  if (keyDown("left")) {
    sprite.x = sprite.x-5;
    sprite.mirrorX(-1);    
  }
  if(sprite.x-cactus.x>200) cactus.x=sprite.x+200;
  if(cactus.x-sprite.x>200) cactus.x=sprite.x-200;
  if(sprite.x-fence.x>200) fence.x=sprite.x+200;
  if(fence.x-sprite.x>200) fence.x=sprite.x-200;
}

                        

Syntax

camera.on();

Returns

No return value. Possibly changes output in the display after drawSprites() is called.

Tips

  • The camera is automatically turned on at the start of each draw() loop.

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