How to detect collisions between a moving point and the stroke of an arbitrary boundary shape?

Viewed 94

I want to draw a circle(for example) and create a couple of points inside that circle. The points are moving randomly, but when they hit the circle's stroke, they should either stop or go inverse or react in some way (it's not that important). I know it would be easy to do with rect-like shapes, but I want to draw inside custom shapes like stars or flower.

1 Answers

To find out if point inside the circle or not you just need to calculate distance from center of circle to point itself. If that distance less then radius - point inside circle.

Fun example:

let c, r;
let points = [];

function setup()
{
  createCanvas(200, 200);
  r = 50;
  c = createVector(100, 100);
  let pos = createVector(95, 110);
  let v = p5.Vector.random2D();
  points.push({p: pos, v: v});
}

function draw()
{
  background(0);
  points.forEach(point => {
    point.p.add(point.v);

    if(point.p.dist(c) > r) {
      let n = point.p.copy().sub(c).normalize();
      let d_n = point.v.dot(n);
      point.v = p5.Vector.sub(n.mult(2).mult(d_n), point.v).mult(-1);
      //pv.mult(-1);
    }
    circle(point.p.x,point.p.y,5);
  });
  
  noFill();
  stroke(255);
  circle(c.x,c.y, r*2);
  
}

function mouseClicked() {
  let p = createVector(mouseX, mouseY);
  if (p.dist(c) < r) {
    points.push({
      p: p,
      v: p5.Vector.random2D(),
    });
  }
  // prevent default
  return false;
}
<script src="https://github.com/processing/p5.js/releases/download/v1.4.0/p5.min.js"></script>
click inside circle

Boring example:

let c, radius;
function setup()
{
  createCanvas(200, 200);
  c = createVector(100, 100);
  radius = 50;
}

function draw()
{
  background(0);
  let point = createVector(mouseX, mouseY);

  let distance = c.dist(point);
  if (distance > radius) {
    fill("red"); 
  } else {
    fill("green");
  };
  circle(c.x, c.y, radius * 2);
  
  // just rendering text :)
  stroke(255);
  line(point.x,point.y, c.x,c.y);
  stroke(0);
  fill(200)
  push()
  translate(p5.Vector.add(c, p5.Vector.sub(point, c).div(2)));
  text(distance.toFixed(2),0,0)
  pop()
  
  text("Move your mouse",20,10);
}
<script src="https://github.com/processing/p5.js/releases/download/v1.4.0/p5.min.js"></script>

Related