简体   繁体   中英

Detect a collision with the edge of a circle

I am using a script to generate random particles within a circle based on it's radius. What I would like to do next is detect when the particle collides with the circles edge.

I'm guessing I need to use a for loop to store the coordinates of the circles circumference in an array but I'm unsure what math is needed to do this.

Here's what I've got down from the answer below. It doesn't seem to be working though:

Variable par is a particles moving with the circle, emitters contains x,y, positions of the centre of the circle while the prop height contains the radius.

var fromC = Math.sqrt( (par.y-(emitters[i].y ) )^2 + (par.x- (emitters[i].x))^2); 

if(fromC >= emitters[i].height){
    par.vx *= -1;
    par.vy *= -1;
}

Thanks in advance.

The issue is with your square operation, ^ is NOT power operator in javascript.

Use this:

var fromC = Math.sqrt( Math.pow((par.y - emitters[i].y), 2) + Math.pow((par.x - emitters[i].x), 2) ); 

if(fromC >= emitters[i].height){
    par.vx *= -1;
    par.vy *= -1;
}

只需计算点和圆心之间的距离(平方根((y2-y1)^ 2 +(x2-x1)^ 2)并与半径比较

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM