2017-07-04 5 views
1

私は、パーティクルオブジェクトを衝突させ、スレートオブジェクトに反射させようとしています。p5.jsの2つの異なる形状のオブジェクトの衝突検出

私が楕円を使用したいのであれば、私は半径変数を作成することができます - 矩形ではできませんので簡単です。

これは距離変数と関係がある、私はそれを把握することはできません。

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); 
    } 

    } 
} 

答えて

0

パーティクルがポイント(またはポイントとして表すことができる)の場合、点矩形の衝突検出を使用する必要があります。基本的には、ポイントが左端と右端の間、および長方形の上端と下端の間にあるかどうかを確認する必要があります。

if(pointX > rectX && pointX < rectX + rectWidth && pointY > rectY && pointY < rectY + rectHeight){ 
    //the point is inside the rectangle 
} 

粒子が楕円形であり、あなたがその楕円の半径に考慮する必要がある場合は、あなただけの衝突のために、四角形などの粒子を表現する方がいいでしょう。次に、四角形の矩形の衝突検出を使用することができます。これはバウンディングボックスとも呼ばれ、衝突検出を処理する最も一般的な方法の1つです。

if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){ 
    //the rectangles are colliding 
} 

恥知らずな自己宣伝:私はhere可能な衝突検出のチュートリアルを書きました。処理のためですが、P5.jsの場合もすべて同じです。

+0

これは素晴らしい声援です。 –