将球向上和向右移动

Move ball up and right

我以前的程序弹跳一个球,但现在我希望用户能够随时上下左右移动它。到目前为止,我的右按钮和下按钮可以工作,但左按钮和上按钮的逻辑不起作用。

在我看来,以下代码是正确的,但我猜它不是

function moveU() {
    var currentTopPos = parseInt($("#ball").css('top'));
    // define the new position
    var newBottomPos = currentTopPos - velocity_y;

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

    $("#ball").css('top', newBottomPos + 'px');
    maxTop = parseInt($("#outerbox").css('top')) - parseInt($("#outerbox").css('border-left-top')) - parseInt($("#ball").css('top'));
}

我目前没有错误。球就是不动。

https://jsfiddle.net/W4Km8/4931/

您更改太多:例如,只需复制 moveR() 并将加号替换为减号: https://jsfiddle.net/svArtist/pnuqyyqh/

    function moveL() {
    // Read the current left position of the ball
    var currentLeftPos = parseInt($("#ball").css('left'));

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

    // 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 *= 0; // multiply the value by -1

    // update the position
    $("#ball").css('left', newLeftPos + 'px');

    // display number of seconds played


  }

这里有一些建议。


创建一个 move 函数,它将球移动给定的 xy 量,然后使用计时器调用自身:

function move(x, y) {
  //movement code   
  moveBall= setTimeout(function() {
    move(x, y);
  },20);
}


然后你可以有一个单一的功能来处理所有的移动按钮:

$('.btn-primary').click(function() {
  $('.btn-primary').prop('disabled', false);
  $(this).prop('disabled', true);
  clearInterval(moveBall);
  switch(this.id) {
    case 'moveU': move(0, -velocity_y); break;
    case 'moveD': move(0,  velocity_y); break;
    case 'moveL': move(-velocity_x, 0); break;
    case 'moveR': move( velocity_x, 0); break;
  }
});

不是确定球的当前位置并添加偏移量,而是使用 jQuery 的 css() 语法来改变相对量 (+=):

$('#ball').css({
  top : '+=' + y,
  left: '+=' + x
});


如果球在其容器外,只需反转相对方向 (-=):

ofs= $('#ball').offset();

if(ofs.left < maxLeft || ofs.left+ballWidth  > maxRight ||
   ofs.top  < maxTop  || ofs.top +ballHeight > maxBottom
  ) {
  $('#ball').css({
    top : '-=' + y,
    left: '-=' + x
  });
}


我已将这些建议放在一起 Fiddle:

http://jsfiddle.net/s1v128Lh/