2015-05-06 29 views
1

這是上一個問題中我的程序的更新版本。 目前,我試圖確定爲什麼監視我的盒子div的頂部和底部我MAXTOP變量返回NaN的值球在邊界外跳動

當我運行我的程序,球反彈的左側和右側牆壁上,但是當它到達底部/頂壁離開。有什麼建議,爲什麼?

我的變量如下:

currentLeftPos = parseInt($("#ball").css('left')); 
currentTopPos = parseInt($("#ball").css('top')); 

// define the new position 
var newLeftPos = currentLeftPos + velocity_x; 

//alert(velocity_x); 
var newTopPos = currentTopPos + velocity_y; 

//alert(velocity_y); 
// If the left position is greater than or equal to the maximum distance allowed or 

// less than or equal to zero, then change the direction. 

if(newLeftPos >= maxLeft || newLeftPos <= 0) 
    velocity_x *= -1; // multiply the value by -1 

if(newTopPos >= maxTop || newTopPos <= 0) 
    velocity_y *= -1; // multiply the value by -1 

maxLeft = parseInt($("#outerbox").css('width')) -parseInt($("#outerbox").css('border-left-width')) - parseInt($("#ball").css('width')); 

maxTop = parseInt($("#outerbox").css('top')) -parseInt($("#outerbox").css('border-left-top')) - parseInt($("#ball").css('top')); 

https://jsfiddle.net/W4Km8/4884/

+1

這是「邊框頂部寬」,而不是邊界-top-height – Taplar

+0

調試它並不困難,告訴你'border-top-height'是未定義的。沒有像這樣的CSS屬性 –

+0

在這樣的情況下,你的結果是意想不到的,把它的每一部分和console.log()它通常是有幫助的,以確保你得到你所期望的。 – Taplar

回答

1

變化border-top-width而不是將你的第一個的解決方案問題。

併爲您的第二個問題的解決方案是:

var maxRight = parseInt($("#outerbox").css('width')) +maxLeft; 
var maxBottom = parseInt($("#outerbox").css('height')) - parseInt($("#ball").css('height')); 

更新上值當改變維和:

if(newTopPos >= maxBottom || newTopPos <= 0) 
    velocity_y *= -1; // multiply the value by -1 

if(newTopPos >= maxRight || newTopPos <= 0) 
    velocity_y *= -1; // multiply the value by -1 

檢查Fiddle Here.

+1

什麼是有趣的是,在我試圖執行一個底部,但因爲我的maxLeft一行代碼工作了左對,我認爲一條線可以用於頂部和底部。謝謝你解釋這個! – narue1992

1

沒有財產邊界高度

var maxTop = parseInt($("#outerbox").css('height')) -parseInt($("#outerbox").css('border-top-width')) - parseInt($("#ball").css('height')); 

alert(maxTop); 

http://www.w3schools.com/cssref/pr_border-width.asp

enter image description here

更新: 一個工作的jsfiddle來演示如何在框中反彈球,它展示瞭如何創建一個基本的彈跳球遊戲

border-top-height

http://jsfiddle.net/49qd7q8h/2/

+0

我對邊界屬性並不完全熟悉,因此很好地瞭解所有不同的邊界屬性。我很欣賞向我展示這一點! – narue1992

+0

我剛剛更新我的答案用的jsfiddle看看它是如何工作的,它會告訴你如何創建一個基本的彈跳球遊戲 – ustmaestro