我之前的程序反弹球,但现在我希望用户能够随时上下左右移动它。到目前为止,我的向右和向下按钮都工作,但我左右的逻辑没有。
在我看来,以下代码是正确的,但我猜它不是
v
我目前没有错误。球根本不动。
答案 0 :(得分:1)
Here are some suggestions.
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
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()
):
+=
$('#ball').css({
top : '+=' + y,
left: '+=' + x
});
):
-=
答案 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
}