xxxxxxxxxx
75
let _x = 0;
let _y = 0;
let _xVelocity = 0.0; // in pixels / s
let _yVelocity = 0.0; // in pixels / s
let _xAccel = 0;
let _yAccel = 10;
let radius = 20;
function setup() {
createCanvas(400, 400);
_x = width / 2;
_y = height / 2;
_lastDrawTimestamp = millis();
frameRate(60);
}
function draw() {
let deltaTimeInSecs = (millis() - _lastDrawTimestamp) / 1000.0;
_lastDrawTimestamp = millis();
background(220);
// physics
// Calculate new speed
_xVelocity += _xAccel;
_yVelocity += _yAccel;
// Calc distance travelled in that time
let xDistance = _xVelocity;
let yDistance = _yVelocity * deltaTimeInSecs;
//Add to position
_x += xDistance;
_y += yDistance;
//print(xDistance, yDistance);
if(_x < 0){
_x = 0;
_xVelocity *= -1;
// add in dampening force from wall
}else if(_x > width){
_x = width - radius;
_xVelocity *= -1;
// add in dampening force from wall
}
if(_y < 0){
_y = 0;
_yVelocity *= -1;
}else if(_y > height){
_y = height - radius;
_yVelocity *= -0.8;
}
// rendering
fill(255);
circle(_x, _y, radius);
fill(50);
text(nf(deltaTimeInSecs, 1, 3), 10, 10);
text("Frame rate: " + nf(frameRate(), 1, 1), 10, 20);
//print(_xVelocity, _yVelocity);
}