Enemy object not moving!

Hi. i decided one day to make the dinosaur game in the chrome browser. it all worked fine, until i made the cactus.(i suck at programming, so don’t judge) The problem is that he( the cactus) is not moving, even if i assigned a velocity, gravity, and a location.

here is the code for the cactus

PVector locat2;
PVector velocityObst;
PVector gravity2;


class Cactus 
{
  {
    locat2 = new PVector(1000, 500);
    gravity2 = new PVector(0, 0.2);
    velocityObst = new PVector(-5, 0);

    velocityObst.add(gravity2);

    locat2.add(velocityObst);

    if (locat2.y > 500) {
      locat2.y = 499;
    }

    stroke(255);
    strokeWeight(2);
    fill(0);
    rect(locat2.x, locat2.y, 39, 56);
  }
}

and if you need the code for the main character, here it is:

PVector location;
PVector velocity;  
PVector gravity;   
PVector upforce;

void setup() {
  size(1100, 600);
  location = new PVector(50, 500);
  velocity = new PVector(0, 0);
  gravity = new PVector(0,0.2);
  upforce = new PVector(0, -5.4); 
  
}

void jump() {
  location.add(upforce);
}

void draw() {
  background(255);
  
  new Cactus();

  location.add(velocity);

  velocity.add(gravity);

  if ((location.x > width) || (location.x < 0)) {
    velocity.x = 0;
  }

  if (location.y > 500) {
    velocity.y = 0;
  }
  
  stroke(255);
  strokeWeight(2);
  fill(127);
  rect(location.x, location.y, 39, 56);

  if (locat2.x == location.x){
    jump();
  }
 
  
  if (keyPressed) {
    if (key == ' ') {
      jump();
    }
  } else {
  }

}
1 Like

by the way, i want the cactus to move toward the player, and not the other way around.

Well keeping your code as similar as possible move the line locat2 outside the class so it looks like this:

PVector locat2 = new PVector(1000, 500);;
PVector velocityObst;
PVector gravity2;


class Cactus 
{
  {
    gravity2 = new PVector(0, 0.2);
    velocityObst = new PVector(-5, 0);

    velocityObst.add(gravity2);

    locat2.add(velocityObst);

    if (locat2.y > 500) {
      locat2.y = 499;
    }

    stroke(255);
    strokeWeight(2);
    fill(0);
    rect(locat2.x, locat2.y, 39, 56);
  }
}

Because every time you create a new class instance it still has the same location of the old one resulting in the cactus not moving at all.

2 Likes

i’m going try it out

thank you, you helped me

how do i close off a topic

how would i make a new cactus if the locat2.x == 250