2017-10-21 82 views
-1

我有以下的「遊戲」:JavaScript的碰撞檢測與CSS動畫

jsfiddle

function update() { 
    coyote.applyForce(gravity); 
    coyote.edges(); 
    coyote.update(); 
    cactus.update(); 
    if (coyote.intersects(cactus)){ 
    alert("colision"); 
    } 
} 

的問題是,當狼跳躍,股利增加它的大小和存在導致一些空白點也會碰撞。

有什麼辦法可以改善碰撞檢測嗎?我試圖實現內部hitbox,但我沒有弄清楚如何。

+2

是的。計算交點。使用這種尺寸的畫布來渲染兩個元素的特定區域,併爲這兩個元素中的每一個元素提取原始像素數據。現在搜索數據,逐像素(4字節),這兩個數組中包含一個值(除0) – Thomas

回答

1

花了一段時間才明白你在做什麼。

但是,如果你爲你的播放器採取靜態寬度和高度。它應該解決你的問題。

constructor(){ 
    this.coyote = new Entity(); 
    this.coyote.pos.set(0,222); 
    this.coyote.vel.set(0,0); 
    this.coyote.acc.set(0,0); 
    this.coyote.width = 78; 
    this.coyote.height = 128; 
    this.isGrounded = true; 
    this.state = States.RUNNING; 
} 

intersects(other) { 
    let div = document.getElementById("player"); 
    let left = this.coyote.pos.x; 
    let right = this.coyote.width; 
    let top = this.coyote.pos.y; 
    let bottom = this.coyote.height; 
    let oLeft = other.left; 
    let oRight = other.right; 
    let oTop = other.top; 
    let oBottom = other.bottom; 
    return !(left > oRight || right < oLeft || top > oBottom || bottom < oTop); 
} 

這應該適合你。

溫馨提示:
1.使用作爲起始畫布。
2.最重要的是可讀代碼。
3.意見和總結

+0

在這項工作中,我不允許使用畫布,這將是如此容易哈哈,也是啊原代碼被分割成多個js文件,但jsfiddle不允許這樣做(據我所知) –

+0

哦,很酷的hooped我幫你了^。^ – RensvWalstijn