Need Help Understanding Code (Gravity)


#1

I’m fairly new to processing and while attempting to code Gravity into my assignment I came across a template for coding gravity and acceleration. The problem is im not sure what the point of the last line y=height is.

float x=240; //position of square
float y=0; // position of square
float speed=1; // Velocity/Speed of Square
float gravity=0.1; //Change in the speed i.e acceleration

void setup(){
  size(480,720);
}

void draw(){
  background(255);
  fill(175);
  stroke(0);
  rectMode(CENTER);
  rect(x,y,10,10);
  y=y+speed; 
  speed=speed+gravity;
  if (y>height){
    speed=speed*-0.95;
    y=height;
  }
}

What exactly does y=height do to the program, id assume it sets the position of the square to the height of the page but when I run the code it doesn’t seem to do that.


#2

Notice that the y = height; is happening inside the if( y > height ){ conditional statement. What does this say in words? Well, if the square has gone off the bottom of the screen (that’s the if( y > height ) { bit), then the speed needs to change (that’s the speed = speed * -0.95; bit), and the square needs to be relocated to the bottom of the screen (y=height;).

Why do this? Consider: The square might be moving down very fast! If it’s moving down at 1000 pixels a frame, one frame it might be near the bottom (say, 20 pixels above it), and the next frame it would be 980 pixels below it! In this case, what would happen? Well the speed would change to being 950 upward… BUT THAT’S NOT ENOUGH TO GET IT TO JUMP BACK INTO THE WINDOW! Setting the position back to the limit causes the square to jump back to a valid position, so that it won’t ever fly outside the boundary on accident.

This is an exaggeration, of course. Maybe your square’s speed is limited elsewhere. But fixing the position when changing the speed at a moment of bouncing is a good practice to get into, otherwise you might find that your objects get “stuck” at the boundary, or fly right through it!


#3

Remember to hit ctrl-t regularly in processing which gives you better indents


#4

Also, to see those indents when you cut-paste into the forum, always highlight your code and use the </> button on the forum editor – or press the button first and then paste your code in between the ``` fence markers.