2013-06-04 91 views
1

我正在創建一個簡單的遊戲,並且當前卡在我有一個名爲「盒子」的div和其內部的圖像,稱爲「降落傘」,當遊戲開始降落傘時應該移動在div使圖像在div內隨機移動

的邊界內隨機我的代碼:

<div id="box"> 


    </div> 

<script type="text/javascript"> 
var ToAppend = "<img src='Parachute.gif' width='25px' height='25px' class='Parachute' /> "; 
     setInterval(function() { 
      for (var i = 1; i <= 2; i++) { 
       $("#box").append(ToAppend); 
       MoveParticles(); 
      } 
     }, 3000); 

     function MoveParticles() { 
       $(".Parachute").each(function() { 
       var x = Math.floor(Math.random() * 400); 
       var y = Math.floor(Math.random() * 400); 

       $(this).animate({ "left": x + "px" }, "slow"); 
       $(this).animate({ "top": y + "px" }, "slow"); 
      }); 
     } 
     <script> 
+0

我會在Canvas中渲染圖像。不建議使用圖像。 – dotTutorials

回答

4

你似乎動畫#box,不.Parachute

Here's a demo to get you in the right track

//let's build the chutes 
for (var i = 0; i < 50; ++i) { 
    $('<div/>', { 
     class: 'chute' 
    }).appendTo('#box'); 
} 

//cache a few static values 
var box = $('#box'); 
var width = box.width(); 
var height = box.height(); 
var chute = $('.chute'); 

//our main animation "loop" 

chute.each(function foo() { 

    //generate random values 
    var top = (Math.random() * height) | 0; 
    var left = (Math.random() * width) | 0; 
    var time = Math.random() * (800 - 400) + 400 | 0; 

    //animate 
    //we introduce a random value so that they aren't moving together 
    //after the animation, we call foo for the current element 
    //to animate the current element again 
    $(this).animate({ 
     left: left, 
     top: top 
    }, time, foo); 
}); 
+0

請檢查我的編輯,但仍然不能正常工作 – Sora

+0

@Sora更新了我的答案 – Joseph