2015-01-02 67 views
-1

LIVE DEMO彈跳球算法問題用JavaScript

我綁使球這是一個div反彈向左一旦從右邊過來,但它仍然回到右邊,我知道有太多許多類似的問題誰給了這個解決方案,但他們都在實施canvas這不是我的情況,我這樣做的方式似乎是對的,但就像你可以在現場演示中看到球仍然回到右邊,在這裏是代碼:

var speed = 15, 
    directionTop = 1, 
    directionLeft = 1; 
setInterval(function(){ 


    var ballElement = document.getElementsByClassName('ball')[0], 
     containerElement = document.getElementsByClassName('mainDiv')[0], 
     playersTestRebounce = document.getElementsByClassName('player')[0]; 


    if (ballElement) { 

     var boxLeftPos = ballElement.offsetLeft, 
      boxRightPos = boxLeftPos + ballElement.offsetWidth, 



      offsetContainer = containerElement.offsetWidth + 40; 
      offsetContainerTop = containerElement.offsetTop; 


      if (boxRightPos > offsetContainer) { 
       directionTop = 1; 
       directionLeft = -1; 
      } 

      if (boxLeftPos < -40) { 
       directionTop = 1; 
       directionLeft = 1; 
      } 

       if (ballElement.offsetTop > playersTestRebounce.offsetTop && ballElement.offsetTop < (playersTestRebounce.offsetTop + 70) && ballElement.offsetLeft < (playersTestRebounce.offsetLeft + 12)) {     
         directionTop = 1; 
         directionLeft = 1; 
       } 

      if (ballElement.offsetTop > 390) { 
       directionTop = -1; 
       directionLeft = 1; 
      } 

      if (ballElement.offsetTop < 0) { 
       directionTop = 1; 
       directionLeft = 1; 
      } 


      ballElement.style.left = (boxLeftPos + speed * directionLeft) + 'px'; 
      ballElement.style.top = (ballElement.offsetTop + speed * directionTop) + 'px'; 




      /*cordinators = getPos(ballElement); 
      console.log("ball X : "+ cordinators.y + " ball Y :" +cordinators.x);*/ 

      /*random = Math.floor((Math.random() * 376) + 6); 

      if (boxLeftPos < -40 || boxRightPos > offsetContainer) { 
       ballElement.style.top = random + 'px'; 
      } */ 


    } 
}, 100); 
+1

你不應該更改左右/在頂部或底部牆壁上彈跳時的右側運動;在左右牆彈跳時也不應改變上/下運動。 – AakashM

+0

但它似乎以這種方式工作時,球從左到右,而不是在另一個方向! –

+2

它將適用於從左到右的第一次反彈,因爲您在彈跳底部時設置directionLeft = 1 – dwana

回答

1

基本彈跳可以減少到這個http://jsfiddle.net/52b261e2/1

if (ballElement.offsetTop > 390 ||ballElement.offsetTop <0) { 
    directionTop *=-1; 
} 

if (boxLeftPos <0 ||boxRightPos>600) { 
    directionLeft *=-1; 
} 

當你到達底部或頂部它-1變化1和-1 1 同樣適用於左到右

*編輯忘了更新小提琴