2

私はこのフィドルを持っています: http://jsfiddle.net/ps4t9/4/

$(window).keydown(function (e) {
        if (e.which == 38) { player.animate({ top: '-=20px' }); shuriken.animate({ top: '-=20px' }); } // up
        if (e.which == 40) { player.animate({ top: '+=20px' }); shuriken.animate({ top: '+=20px' }); } // down
        if (e.which == 32) { shuriken.animate({ left: '+=280px' });} // space bar hit

    });

プレイヤーがコンテナの境界の外に出ないようにするにはどうすればよいですか?

4

6 に答える 6

1

これを試してください:http://jsfiddle.net/ps4t9/11/

$(document).ready(function () {
  var player = $("#Player"),
      shuriken = $("#Shuriken"),
      container = $("#Container"),
      w = container.width() - shuriken.width();

  $(window).keydown(function (e) {
    if (e.which == 38) {
      if (parseInt(player.css('top')) > 10) {
        player.animate({ top: '-=20px' });
        shuriken.animate({ top: '-=20px' });
      }
    } // up
    if (e.which == 40) {
      if (parseInt(player.css('top')) < 270) {
        player.animate({ top: '+=20px' });
        shuriken.animate({ top: '+=20px' });
      }
    } // down
    if (e.which == 32) { 
      if (shuriken.css('left') != '249px') {
        shuriken.animate({ 'left' : '+=280px' });
      }
    }
  });
});

ただし、キーを押しながら移動が速すぎると壊れます。また、値を少し調整する必要がある場合もあります。

于 2013-07-20T07:27:11.510 に答える
1

if ステートメントを使用できます

if (e.which == 32){ 
if(shuriken.css('left') != '249px'){
shuriken.animate({ 'left' : '+=280px' });
}
}

フィドル: http://jsfiddle.net/Hive7/ps4t9/5/

于 2013-07-20T07:27:16.223 に答える
0

ご協力いただきありがとうございますが、深い瞑想と検索を行った後、なんとか機能させることができました。ここで最終的なjsfiddleです:http://jsfiddle.net/ps4t9/15/ありがとう

 function newv(v, a, b) {
            var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);

            return n < 0 ? 0 : n > w ? w : n;
        }



        $(window).keydown(function (e) {
            d[e.which] = true;
            if (e.which == 32) {

                if (!shurikenHitBorder) {
                    shuriken.animate({ left: '+=280px' }, 'fast');

                    shuriken.fadeIn(100);
                }
                shurikenHitBorder = true;
            }


          });
        $(window).keyup(function (e) { d[e.which] = false; });

        setInterval(function () {
            box.css({top: function (i, v) { return newv(v, 38, 40); }});
        }, 20);
于 2013-07-20T09:52:22.293 に答える
-1

必要な変更を加えてJSFiddleを編集 しました。これは役に立ちますか?さらに説明が必要な場合は私に尋ねてください...

最適な境界を計算するのに役立つようにこれらを追加しました...

posDelta = 20, // amount of change in position
playerOffset = player.height() * 0.5,
playerPos = player.position().top,
maxTop = posDelta,
maxBottom = container.height() - (posDelta + playerOffset);
于 2013-07-20T08:04:00.913 に答える