SIMPLE CODE FOR COLLISION DETECTION
The simple code below is useful for collision detection of a small number of objects, but can also work for a larger number. Feel free to modify or expand the code or share your contribution and suggestions.
This simple code is executed in p5 JavaScript editor.
//***************
Set up the canvass
var Items =[]; function setup() { createCanvas(600, 400); for (let i = 0; i< 100; i++ ){ Items[i] = new Item(random(width), random(height)) } }
Draw the objects
function draw(){ background(0); for (let p of Items){ p.move(); p.showCollision(); p.makeHighlight(false); for (let other of Items){ if (p!== other && p.intersects (other)){ p.makeHighlight(true); } } } }
Define the item class
class Item{ constructor(x, y){ this.x = x; this.y = y; this.r = 8; this.highlight = false; } intersects(other){ let d = dist (this.x, this.y, other.x, other.y); return (d < this.r + other.r); } makeHighlight(val){ this.highlight=val; } move(){ this.x+=random(-1, 1); this.y+=random(-1, 1); } showCollision(){ noStroke(); if (this.highlight){ fill(0, 255, 255); }else { fill(255); } ellipse(this.x, this.y, this.r); } }
No comments:
Post a Comment