xxxxxxxxxx
98
// Example adapted from Jeffrey Thompson:
var mouseDiff, hit = false;
const poly = Array(8).fill(); // stores the vertices for our polygon.
const randomPoly = []; // stores the vertices for our random-sided polygon.
let balloon
class Sprite {
constructor(x, y, image) {
Object.assign(this, { x, y, image })
this.poly = [
{x: 20, y: 100},
{x: 200, y: 110},
{x: 80, y: 30},
{x: 40, y: 50},
{x: 20, y: 30},
]
}
draw() {
image(this.image, this.x, this.y)
beginShape()
for (let {x, y} of this.poly) {
vertex(this.x + x, this.y + y)
}
endShape(CLOSE)
}
move(x, y) {
this.x = x
this.y = y
}
collided() {
}
}
let zuko
function preload() {
balloon = loadImage("Balloon.png")
}
function mouseMoved() {
zuko.x = mouseX
zuko.y = mouseY
}
function setup() {
createCanvas(500, 400);
//collideDebug(true); // enable debug mode
zuko = new Sprite(50, 50, balloon)
mouseDiff = createVector(); // temp vec for randomPoly[]
// Generate an 8-sided uniform polygon:
const angle = TAU / poly.length;
for (var i = 0; i < poly.length; ++i) {
const a = angle * i;
const x = cos(a) * 100 + 300;
const y = sin(a) * 100 + 200;
poly[i] = createVector(x, y);
}
// Generate a random polygon:
for (var a = 0; a < 360; a += random(15, 40)) {
const t = radians(a);
const x = cos(t) * random(30, 50);
const y = sin(t) * random(30, 50);
randomPoly.push(createVector(x, y));
}
}
function draw() {
background(255);
zuko.draw()
// Draw the polygon by iterating over the 8 created vectors{x, y} stored in poly[]:
beginShape();
for (const { x, y } of poly) vertex(x, y);
endShape(CLOSE);
// Update random polygon to mouse position:
mouseDiff.set(mouseX, mouseY).sub(randomPoly[0]);
for (const vec of randomPoly) vec.add(mouseDiff);
// Draw the random polygon from the created vectors{x, y} stored in randomPoly[]:
beginShape();
for (const { x, y } of randomPoly) vertex(x, y);
endShape(CLOSE);
hit = collidePolyPoly(poly, randomPoly, true);
// Vector version does the same thing, here for completeness:
// hit = collidePolyPolyVector(poly, randomPoly, true);
stroke(hit ? color('red') : 0);
print('colliding?', hit);
}