How to have an image randomly appear

edited August 2015 in How To...

Hello - apologies in advance if this query has already been answered or isn't in the right format etc. etc. - I'm new!

I'm building a game where an animal collects carrots and apples which then gains points for the user. Whats the best way to have the images of a carrot and an apple appear at random?

Thank you!

Answers

  • you can say

    int imgX, imgY; 
    
    imgX=random(width); 
    imgY=random(height); 
    
    image(imgCarrot, imgX, imgY);
    
  • when your game is a grid, you need to make the random on the grid.

    when your animal collects carrots you have to have an array or better ArrayList to store the carrots with position

  • Thanks for this. My background is currently an image that gives the illusion that its moving.

    imageMode(CORNER);
    image(backImg, x, 0);
    image(backImg, x+backImg.width, 0);
    

    Is it possible to have a grid on top of this?

  • it sure is possible

    but it is not necessary to have a grid

    are the carrots supposed to move with the background? Probably.

  • old version

    float imgX, imgY; 
    PImage imgCarrot=null;
    
    size(660, 500);
    
    imgX=random(width); 
    imgY=random(height); 
    
    if (imgCarrot!=null) { 
      image(imgCarrot, imgX, imgY);
    }
    else {
      rect(imgX, imgY, 13, 12);
    }
    
    //
    
  • Answer ✓

    this version places the carrot in steps of 20

    so when you are on a grid, it's on a grid

    but you don't need a grid

    just say

    if (dist(animalX,animalY,carrotX,carrotY)<25) 
         println ("Hooray");
    

    here the new version

    float helperImgX, helperImgY;
    float imgX, imgY; 
    PImage imgCarrot=null;
    
    size(660, 500);
    
    helperImgX=int(random(width/20)); 
    helperImgY=int(random(height/20)); 
    
    imgX=20 * helperImgX;
    imgY=20 * helperImgY;
    
    println (imgX+","+imgY);
    
    if (imgCarrot!=null) { 
      image(imgCarrot, imgX, imgY);
    }
    else {
      rect(imgX, imgY, 13, 12);
    }
    
    // -------------------------
    
  • The carrots should appear at random so that they can be 'collected' by the user but the background is the only thing that moves. There is a horse which is moved by the user to collect the carrots...

  • Ok cool thanks, I'll give this a go!

Sign In or Register to comment.