【问题标题】:How can I generate a random speed for my racers in jQuery?如何在 jQuery 中为我的赛车手生成随机速度?
【发布时间】:2013-03-29 01:00:24
【问题描述】:

我正在尝试创建一个基本的赛车手,让两个精灵相互对抗。经过一些调整,我让我的赛车手以慢速向右移动了 550 像素

有我的赛车手和允许他们比赛的按钮

<center><button id="race">Race!!</button></center>
<div class="kimo"><img id="kimo" src="images/kimo.gif"  alt="Kimo" height="80"></div>
<div class="kahuna"><img id="kahuna" src="images/kahuna.gif"  alt="Kahuna" height="80"></div>

这是动画它们的脚本

<script>
$("#race").click(function(){
$(".kimo").animate({"left": "+=550px"}, "slow");
$(".kahuna").animate({"left": "+=550px"}, "slow");
});
</script>

现在这里是速度明显“慢”的地方,但我想让它们在单击按钮时生成随机速度,并且只使用一次动画。例如,赛车手总共移动了 550 像素。

我需要完成的其他事情:无论谁先到达 550 像素的末尾,都会出现说明 Kimo 或 Kahuna 获胜的文字。

感谢任何帮助。

【问题讨论】:

    标签: jquery animation random


    【解决方案1】:

    您可以使用Math.random 生成速度,但您首先必须计算出最大和最小速度 - 最小速度非常重要,因为 Math.random 有可能生成一个非常小的数字,以至于动画将需要任意长的时间才能完成。

    [编辑]:OP 询问是否可以只触发一次动画 - 我添加了 .unbind() 方法,并为该函数分配了一个处理程序。

    <script>
    // Assign handler name, so that we can unbind it specifically
    $("#race").click(function animateSprite(){
        // Unbind after first click
        $(this).unbind('click', animateSprite);
    
        // Set minimum speed
        var minSpeed = 1000;
    
        // Get random speed
        var kimoSpeed = parseInt(minSpeed + Math.random()*1000, 10),
            kahunaSpeed = parseInt(minSpeed + Math.random()*1000, 10);
    
        // In this case, the lowest possible speed is 1000, 
        // and the highest possible speed is 2000.
        // You are of course free to adjust the speed.
    
        // Animate
        $(".kimo").animate({"left": "+=550px"}, kimoSpeed);
        $(".kahuna").animate({"left": "+=550px"}, kahunaSpeed);
    
        // And if you want to decide who is the fastest, and assuming that you have an element with the id of "announce"
        // Delay announcement by 500ms after the slowest racer
        setTimeout(function(){
            if(kimoSpeed < kahunaSpeed) {
                // Declare Kimo as winner, e.g.
                // $("#announce").text("Kimo has won the race!");
            } else {
                // Declare Kahuna as winner
                // $("#announce").text("Kahuna has won the race!");
            }
        }, Math.max.apply(Math, [kimoSpeed, kahunaSpeed])+500);
    });
    </script>
    

    【讨论】:

    • 非常感谢!这是一个非常有用的答案:)
    • 我尝试在我的代码中实现它,但它们仍然以相同的速度移动。尽管如此,你给了我非常好的信息和洞察力,我会继续努力直到它奏效
    • 实际上,这是我的一个简单错误。它就像一个魅力。现在我只需要确保按钮只工作一次。非常感谢!
    • 如果你想让按钮只工作一次,你可以在click函数中使用$(this).unbind('click');
    • 谢谢特里!您知道是否有任何方法可以将公告推迟到赛后?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    相关资源
    最近更新 更多