球在边界外弹跳

时间:2015-05-06 11:44:31

标签: jquery html css

这是我之前提问的程序的更新版本。 目前我正在尝试确定监视我的box 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/

2 个答案:

答案 0 :(得分: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,演示如何在一个盒子内反弹球,它显示如何创建一个基本的弹跳球游戏

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

答案 1 :(得分:1)

更改border-top-width代替border-top-height将解决您的第一个 NAN 问题。

第二个问题的解决方案是:

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.

相关问题