[英]HTML5 Canvas 2D Frameworks focusing on collision detection and physics
[英]2D collision detection on html5 canvas
我正在嘗試復制一個稱為haxball的游戲,這是一個非常簡單且基本的2d足球游戲。 但是我在碰撞檢測方面遇到了麻煩,我不想使用Box2d之類的引擎,因為它對於我想要的東西來說有點過大了,並且由於我是初學者,所以我只是在練習游戲。
我可以檢查碰撞是否發生,但是無法正確解決。 我遍歷所有對象並檢查它們是否與球相撞,然后將它們放在對象的“邊界”上,以使其不再位於另一個“內部”。 問題來了,因為如果球同時與圓和邊碰撞,它將停留在邊或圓內。
這是圓的沖突解決以及邊緣的檢測和解決的代碼:
this.resolveCollisionCircle = function(circle) {
var nv = circle.pos.sub(this.pos);
nv = nv.setMag(circle.radius + this.radius).add(circle.pos);
this.pos = nv;
// I'll try to add later the bounce effect
}
this.edgeCollision = function() {
if(this.pos.x-this.radius < 0) {
this.pos.x = this.radius;
this.velocity = this.velocity.mult(new Vector(-1, 1));
}
else if(this.pos.x+this.radius > Width) {
this.velocity = this.velocity.mult(new Vector(-1, 1));
}
if(this.pos.y-this.radius < 0) {
this.pos.y = this.radius;
this.velocity = this.velocity.mult(new Vector(1, -1));
}
else if(this.pos.y+this.radius > Height) {
console.log('baixo')
this.velocity = this.velocity.mult(new Vector(1, -1));
}
}
球相應地移動到速度矢量,在這種情況下,球從(-4,0)開始
該錯誤的演示: http : //antoniomc.0fees.us/
也! 如果您可以向我介紹可以教我這些知識的優質畫布教程,我將不勝感激! 我似乎只找到了另一種語言,無論如何對我有幫助,但是偶爾看到畫布碰撞檢測和解決教程將是非常不錯的...
在.resolveCollisionCircle()
,存儲舊位置,更改位置,然后返回到舊位置,如果新位置不在畫布之外,則完全停止球。
this.resolveCollisionCircle = function(circle) {
//previous position
var prevPos = this.pos;
//set new position
var nv = circle.pos.sub(this.pos);
nv = nv.setMag(circle.radius + this.radius).add(circle.pos);
this.pos = nv;
//change back if out of canvas
if ((this.pos.x-this.radius < 0) || (this.pos.x+this.radius > Width) || (this.pos.y-this.radius < 0) || (this.pos.y+this.radius > Height)) {
this.pos = prevPos;
this.velocity = this.acceleration = new Vector(0, 0);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.