2015-05-06 24 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