How to make a moving picture go off the screen and make it come back again

Viewed 56

I am new to processing and I am creating this small game where these stick men try to avoid the attacker. I have added a moving stick man. It goes from bottom to top, but when it reaches the top, it doesn't come back up from the bottom side again, it just disappears. I was wondering what I could do to make this change. Picture for the stick man moving up This is what happens when the stick man go off the screen they don't return back from the bottom


void setup()
{
  size(800,400);
  stick2 = new Stick(10, 200, 2);
  stick3 = new Stick(150,200, 3);
}

void draw()
{
  background(240);
  stick2.render();
  stick2.move();
  stick3.render();
  stick3.move();
}
class Stick
{
 //members?
 int x, y;
 int speedX = 2;
 int speedY = 2;
 int animationcounter = 0; //animation
 PImage img1, img2;
  
 //constructor - load images
 Stick(int x, int y, int speed)
 {
   
   this.x = x;
   this.y = y;
   this.speedX = speed; 
   img1 = loadImage("stick1.png");//loads from .pde source code directory
   img2 = loadImage("stick2.png");

 }
  void render()
 {
   //cycle through images, and back to image1
   
   if (animationcounter >0 & animationcounter <=8)
    { image(img1,this.x,this.y); }
     else if (animationcounter >8 & animationcounter <=20)
    {image(img2,this.x,this.y);  }
    
    else
    {
    image(img2,this.x,this.y);
    }
    
    animationcounter = animationcounter+1;
    if (animationcounter>32)
      animationcounter = 0;
 }
 void move()
 {
   this.y = this.y - speedY; //move rightwards
   if (this.y>height)
     this.y = +img1.height;
 }
}
1 Answers

The problem is that you're not actually checking if the stickman goes above the screen. You're checking if its y value is higher than height, in other words, if it's below the screen.

Example of the coordinates on screen

Also, it would be nice if the image goes completely off the screen before it appears on the other side. To achieve this, your move function should look like this

void move()
{
   this.y = this.y - speedY;

   //image goes above the screen
   if (this.y < 0 - img1.height) //subtract the image height so the image completely disappears before it moves down
     this.y = height + img1.height;
   //image goes below the screen
   if (this.y > height + img1.height)
     this.y = -img1.height;
 }
Related