向上和向右移动球

时间:2015-05-12 21:11:55

标签: jquery html position

我之前的程序反弹球,但现在我希望用户能够随时上下左右移动它。到目前为止,我的向右和向下按钮都工作,但我左右的逻辑没有。

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

v

我目前没有错误。球根本不动。

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

2 个答案:

答案 0 :(得分:1)

Here are some suggestions.


Create a single result2 = animals.filter(function (value) { // letter filter }).filter(function (value) { // length filter }); function, which moves the ball a given move or x amount, and then calls itself using a timer:

y


You could then have a single function that handles all the movement buttons:

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

Instead of determining the current position of the ball and adding an offset, use jQuery's $('.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; } }); syntax for changing by a relative amount (css()):

+=


If the ball is outside its container, simply reverse the relative direction ($('#ball').css({ top : '+=' + y, left: '+=' + x }); ):

-=


I've put these suggestions together in this Fiddle:

http://jsfiddle.net/s1v128Lh/

答案 1 :(得分:0)

你改变了太多:只需复制,例如,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


  }