Strange ball behaviour

I wrote a very simple code that doesn’t work as expected. I could have fixed it with a patch or something similar, however, I am really interested in the logical flaw that leads to the problem.

The issue is that the ball’s height keeps getting smaller, which is not expected.

My sketch is here - openProcessing.org

I have found that the ball’s maximum velocity decreases by one acceleration each time the ball hits the edge of the screen, but I don’t get why.

var y = 100;
var v = 0;
var a = 0.2;
var x = 100;

function setup() {
	createCanvas(windowWidth, windowHeight);
  frameRate (10);
	
}

function draw() {	
	
	ellipse(x, y, 20, 20);
	
        println (v);	
	
	if (y > windowHeight || y < 0){
	v = v * (-1);
	text (v, x,100);
	
	}
	
	/*
	if (x > windowWidth){
	v = v * (-1);
	}
	
	if (x < 0){
	v = v * (-1);
	
	}
	*/
  
	
	v = v + a;
	y = y + v;
    x = x + 1;
}

Hi Alexstrinda,

You get that behavior because your were counting the a value one more time during the descend then during the ascent if it make any sense…

Maybe the fix sill speak more to you. Just substract the a value to your velocity when it is touching the ground:

if (y > windowHeight || y < 0){
  v = v * (-1) - a;
}
1 Like