Vectors not adding?

//I cant figure out how to get the isMoving function to work, im kind of comfortable with p5js and trying to learn processing but it seems there are always small bugs i cant find.

Ground ground;
Character character;
PVector gravity = new PVector(0, 0.05);
float friction = 0.9;
void setup() {
	size(1500, 800);
	ground = new Ground();
	character = new Character(ground);
}

void draw() {
	rect(500, 500, 50, 50);
	while(keyPressed) {
		character.isMoving();
	}
	character.update(ground);
	character.show();
	ground.show();
}


class Ground {
	PVector pos;
	float w, h;
	
	Ground() {
		w = width;
		h = 100;
		pos = new PVector(0, height-h);
	}	

	void show() {
		fill(100, 100, 100);
		rect(pos.x, pos.y, w, h);
	}
}

class Character {
	PVector pos, vel, acc;
	int size;


	Character(Ground other) {
		size = 50;
		pos = new PVector(100, other.pos.y-size);
		vel = new PVector(0, 0);
		acc = new PVector(0, 0);
	}

	//why does it not move?
	void isMoving() {
		while(abs(vel.x) < 10) {
			if(keyCode == RIGHT) {
				PVector add = new PVector(1, 0);		
				acc.add(add);
			}
			else{acc.x *= friction;}
			

		}
	}


	void update(Ground other) {
		vel.add(acc);
		pos.add(vel);
		acc.mult(friction);

		while(pos.y < other.pos.y-size) {
			acc.add(gravity);
		}
	}

	void show() {
		fill(255, 0, 0);
		rect(pos.x, pos.y, size, size);
	}
}
1 Like

-a- for diagnostic can use

println("functionname");

and you will see that your code is blocked in the while loop of the Character.isMoving( )

-b- pls avoid WHILE loops and replace with IF or FOR

-c- pls use a

void keyPressed() {

}

instead keyPressed and keyCode inside draw or other function.

for RUNNING instead single step walking ( your while (keypressed) )
can also use

void setup(){}
void draw(){
  background(200,200,0);
  text("goRight "+goRight,0,10);
}

boolean goRight = false;

void keyPressed() {
  if ( keyCode == RIGHT ) goRight = true;
}

void keyReleased() {
  if ( keyCode == RIGHT ) goRight = false;
}

4 Likes

Thank you very much for the ideas, I fixed it and continuing to learn more

1 Like