Switch between two backgrounds, animation only on the second background and to only play once?

edited August 2016 in p5.js Library Questions

My sketch starts off with a background image, when the mousePressed over an area it changes to a different background and I want my animation to play only on the second screen. This does work, however once the mouse is pressed to go back to the first screen and pressed again to go back to the second screen there are two instances of the animation. How do I get the animation to happen only once each time it is on the second screen? (hopefully I explained that properly, thank you in advance...I have tried but it's not working for me!)

var awake;
var ray;

var radius = 156;
var x = 672;
var y = 356;

var button = false;

function preload() {
  asleep = loadImage("images/asleep.png");
  awake = loadImage("images/lightbulb.png");
  ray = loadAnimation("images/ray_01.png", "images/ray_04.png");
}

function setup() {
  createCanvas(1024, 768);

  frameRate(20);

}

function draw() {


  if (button) {
    background(84, 161, 224);
    image(awake, 0, 0, width, height);

    drawSprites();

  } else {
    image(asleep, 0, 0, width, height);
}
}

function mousePressed() { //executes once at the moment of the event

  var d = dist(mouseX, mouseY, x, y); //checking if touch is inside lightbulb
  if (d < radius) {

    var rays = createSprite(x, 240);
    rays.addAnimation("normal", "images/ray_01.png", "images/ray_04.png");

    button = !button;
  }
}

Answers

  • Answer ✓

    Just when I posted the question I figured out the answer! It works now :)

    var awake;
    var ray;
    
    var radius = 156;
    var x = 672;
    var y = 356;
    
    var button = false;
    var playing = false;
    
    function preload() {
      asleep = loadImage("images/asleep.png");
      awake = loadImage("images/lightbulb.png");
      ray = loadAnimation("images/ray_01.png", "images/ray_04.png");
    }
    
    function setup() {
      createCanvas(1024, 768);
    
      frameRate(20);
    
    }
    
    function draw() {
    
    
      if (button) {
    
        background(84, 161, 224);
        image(awake, 0, 0, width, height);
        drawSprites();
        playing = true;
    
    
      } else {
    
        image(asleep, 0, 0, width, height);
      }
    }
    
    function mousePressed() { //executes once at the moment of the event
    
      var d = dist(mouseX, mouseY, x, y); //checking if touch is inside lightbulb
      if (d < radius) {
    
        if (!playing) {
    
          var rays = createSprite(x, 240);
          rays.addAnimation("normal", "images/ray_01.png", "images/ray_04.png");
        }
    
        button = !button;
      }
    }
    
  • Now how do I mark this question as answered if I answered it myself?? Is my answer the most efficient way to go about it?

Sign In or Register to comment.