2014-07-26 88 views
0

使用HTML5畫布在哪裏將是最好的地方開始移動我的3個球在隨機軌跡(沿着一條平滑的線,沒有跳躍),當他們擊中對方反彈,然後去另一條路徑,直到他們再次擊中對方並再次彈跳。HTML5畫布隨機方向

到目前爲止,我已經在上設置了一個簡單的例子,其中每個球沿着自己的路徑(儘管它們在屏幕上消失)。

目前的軌跡很簡單,只要

function animate(){ 

    // Yellow Circle 
    circles[0].x+=1; 
    circles[0].y+=-1.5; 

    // Blue Cirlce 
    circles[1].x+=-1; 
    circles[1].y+=-1.5; 

    // Red Circle 
    circles[2].x+=1; 
    circles[2].y+=-1; 
    draw(); 

} 

我很想看到一個例子,但也知道什麼方法和計算我應該看

任何幫助表示讚賞

感謝

+1

解釋這不是一個S. O.題。而是在網上搜索教程。 – GameAlchemist

+0

就隨機軌跡而言,這似乎很簡單,只需將您的x和y分量設置爲一定範圍內的隨機浮點數,由您自己確定爲首選。我錯了嗎? –

+0

好的,我已經更新了小提琴,但黃球的行爲過於隨機,當球移動它需要移動增量運動 – Richlewis

回答

5

這個碼是Adam Brookes for adambrookesprojects.co.uk - 06/10/2013>.

012創建個

移動球

function updateBallPos(deltaTime, ballArray) { 
     for (var i = 0; i < ballArray.length; i++) { 
      ballArray[i].lastGoodPosition = ballArray[i].position; // save the balls last good position. 
      ballArray[i].position = ballArray[i].position.add((ballArray[i].velocity.multiply(deltaTime/10))); // add the balls (velocity * deltaTime) to position. 
     } 
    } 

檢測球碰撞

function checkBallCollision(ball1, ball2) { 
     var xDistance = (ball2.getX() - ball1.getX()); 
     var yDistance = (ball2.getY() - ball1.getY()); 
     var distanceBetween = Math.sqrt((xDistance * xDistance) + (yDistance *yDistance)); 

     var sumOfRadius = ((ball1.getRadius()) + (ball2.getRadius())); // add the balls radius together 

     if (distanceBetween < sumOfRadius) { 
      return true; 
     } 
     else { 
      return false; 
     } 
    } 

SEE DEMO HERE

所有的代碼都清楚他HERE

RELATED QUESTION HERE