The goat in my game keeps disappearing!

Hello! In school we are making a game for computer engineering. What I am trying to do is have the goat move on the x axis from side to side. I have used key pressed to do this but everything I stop pressing the key the goat disappears. Does anyone know how to fix this? My program is below:

PImage rainbow;
PImage goatf;
PImage goatb;
int xPos=300;
int y = 35;
int position = 0;

void setup() {
  size(900, 600);
  background(#FFA5B7);
  noStroke();

  rainbow = loadImage ("rain.png");
  goatf = loadImage ("goat2.png");
  goatb = loadImage ("goatb.png");
}

void draw() {

  image(rainbow, 0, 0);


  if (keyPressed && keyCode == LEFT) {
    position = position - 10;
    image(goatb, position, 400);
  } else if (keyPressed && keyCode == RIGHT) { 
    position = position + 10;
    image(goatf, position, 400);
  }


  //this is a part I'm still working on, I also need help with this

  //if(keyPressed && keyCode == UP && keyCode == LEFT) {

  //image(goatb, position, 380);

  //}

  //if(keyPressed && keyCode == UP && keyCode == RIGHT) {

  //image(goatf, position, 380);

  //}



  if (position >= 750) {

    position = 749;
  } else if (position <= 10) {

    position = 11;
  }
}

Answers

  •   if (keyPressed && keyCode == LEFT) {
        position = position - 10;
        image(goatb, position, 400);
      } else if (keyPressed && keyCode == RIGHT) { 
        position = position + 10;
        image(goatf, position, 400);
      }
    

    it's only showing when you press a key because that's what you've told it to do!

    there needs to be an image call that's outside these two conditions.

    the problem is that the image differs depending on the key you've pressed. so you need another variable.

    PImage goat; // global variable, before setup
    
      ...
      if (keyPressed) {
        if (keyCode == LEFT) {
          position = position - 10;
          goat = goatb; // use goatb
        } else if (keyCode == RIGHT) { 
          position = position + 10;
          goat = goatf; // use goatf
        }
      }
      image(goat, position, 400); // draw the relevant goat
      ...
    

    you'll also notice i moved the common bit of the condition outside, just to simplify things.

  • and the new bit, the bit in comments, will be similar. but i see two problems:

    the y position for both UP bits is 380, not 400. so maybe you need a y position variable as well as the (x) position variable and set that to 380 for UP, 400 for non-UP

    you might have problems detecting both UP and LEFT (or UP and RIGHT) being pressed at the same time. might.

  • I'm just confused because it's not working, can you show me an example?

Sign In or Register to comment.