Reputation:
BEFORE YOU READ: THIS IS P5.js https://p5js.org
Ok, a simple form of the question I am asking is this, look at the code below:
function setup() {
createCanvas(1000,650);
}
var x = 0;
function draw() {
background(200,200,200);
if(x+50<750){x+=17;}
fill(0,0,0);
rect(750,0,250,550);
fill(0,0,255);
rect(x,height/2,50,50);
}
As seen if you run it, the square will "run-over" the black barrier rather than stop just next to it, because the increments are of 17, whereas if the increment was 1 , it would perform perfectly. I attempted to vamp the framerate up to 6000 but for obvious reasons this did not work. THIS IS JUST AN EXAMPLE, BUT HOW (I am making platform physics) WOULD I HAVE A DYNAMIC WAY TO MAKE THE SQUARE SMOOTHLY COLLIDE WITH THE BARRIER?
Upvotes: 0
Views: 2246
Reputation: 3431
You should check x
position plus width
of rect to detect collision. If sum is greater than your obstacle position when handle new x
. Here is simplified example of how it can be handled.
function setup() {
createCanvas(1000, 650);
}
var x = 0,
dir = 1,
rectSize = 50;
function draw() {
var acc = 17 * dir,
nextX = x + acc;
if (nextX + rectSize > 750) {
dir = -1;
x = 750 - rectSize;
} else if (nextX < 0 ) {
dir = 1;
x = 0;
}
background(200, 200, 200);
fill(0, 0, 0);
rect(750, 0, 250, 750);
fill(0, 0, 255);
rect(x, height / 2, rectSize, rectSize);
x += acc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.min.js"></script>
There is library p5.collide2D for collision detection, I adivse you to check it out.
Upvotes: 1