我试图让我的粒子物体碰撞和反射我的板岩物体。
如果我想使用一个椭圆,它会很简单,因为我可以创建一个半径变量-不能用一个矩形。
这和距离变量有关,我就是搞不懂。
var div;
var movers;
function setup() {
createCanvas(windowWidth,windowHeight);
background("#FDEDEB");
div = new Slate();
movers = new Particle();
}
function draw() {
background("#FDEDEB");
div.display();
movers.display();
movers.update();
movers.move();
if (movers.hits(div)) {
console.log("hit");
}
}
function Slate() {
this.x = 30;
this.y = height/2;
this.display = function() {
noStroke();
fill("#DF4655");
rect(this.x,this.y, 700, 200);
}
}
function Particle() {
this.pos = createVector(10,0);
this.vel = createVector(0,0);
this.acc = createVector(0.01,0.01);
this.history = [];
this.display = function() {
fill("#DF4655");
point(this.pos.x,this.pos.y);
//beginShape();
for(var j = 0; j < this.history.length; j++) {
var pos = this.history[j];
ellipse(pos.x,pos.y, 5, 3);
}
//endShape();
}
this.update = function() {
var v = createVector(this.pos.x,this.pos.y);
this.history.push(v);
if (this.history.length > 10) {
this.history.splice(0,1);
}
}
this.hits = function(div) {
// BOUNCE OFF SLATE
var d = dist(this.pos.x,this.pos.y,div.x,div.y);
if (d < 0) {
console.log('hits');
}
}
this.move = function() {
this.pos.add(this.vel);
this.vel.add(this.acc);
this.vel.limit(10);
for (var i = 0; i < this.history.length; i++) {
this.history[i].x += random(-2,2);
this.history[i].y += random(-2,2);
}
}
}
发布于 2017-07-04 10:18:25
如果粒子是点(或可以表示为点),则需要使用点-矩形碰撞检测。基本上,您需要检查该点是否位于矩形的左、右边缘和上、下边缘之间。
if(pointX > rectX && pointX < rectX + rectWidth && pointY > rectY && pointY < rectY + rectHeight){
//the point is inside the rectangle
}
如果粒子是椭圆,你需要考虑这个椭圆的半径,那么你最好把粒子表示为矩形,只是为了碰撞的目的。然后可以使用矩形-矩形碰撞检测。这也被称为边界框,它是处理碰撞检测的最常见的方法之一。
if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
//the rectangles are colliding
}
无耻的自我推销:我写了一个关于碰撞检测可用的这里教程。它是用于处理的,但是对于P5.js,一切都是一样的。
https://stackoverflow.com/questions/44911966
复制相似问题