用javascript移动一些东西,让它移动得更慢

时间:2014-11-16 18:37:27

标签: javascript setinterval

我有一个功课,无法解决它。我们必须通过鼠标移动使心脏随机移动。就像在现实世界中一样,它应该在移动时变慢。

我尝试用setInterval实现这一点,但我不能减少Interval,所以它不会减慢速度。这是我的代码,也许有人可以提供帮助:

的script.js

var xpos = 130;
var ypos = 150;
var id1;
var velocity = 1000;
var xstart=5;
var ystart=57;
var xend=8+800-225;
var yend=100+400-125;
var dx = 1;
var dy = 2;
var time = 100;
var add = 0;
var running;

function move(){
    clearInterval(id1);
    var rand1 = Math.random();
    var rand2 = Math.random();

    if(rand1 < 0)
        dx=-dx;

    if(rand2 < 0)
        dy=-dy;
}

function speed(t){
    var id1 = setInterval(function(){
        if(xpos+dx > xend || xpos+dx < xstart)
            dx=-dx;
        if(ypos+dy > yend || ypos+dy < ystart)
            dy=-dy;       
        xpos += dx;
        ypos += dy;
        the_node = document.getElementById('heart');
        the_node.innerHTML = '<div class="blue" style="position:absolute;top:' + ypos + 'pt;left:' + xpos + 'pt;" onmouseover="move();">&hearts;</div>'
        t = add;
        add+=50; 
        console.log(t, add);
        stop();
    },t);
}

的index.html

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        .grey {background-color: #eeeeee; 
            width: 400px; 
            height: 200px;}
        .blue {color: red;
                font-size: 30px;}
        #fang {
            width: 400px;
            height: 200px;
        }
    </style>
    <script src="script.js" type="text/javascript"></script>
    <title>Fang das Herz</title>
</head>
<body>
    <h1>Hausaufgabe: Fang das Herz</h1>
    <div class="grey">
        <div id="heart">
        <div class="blue" style="position:absolute; top:150px; left:130px;" onmouseover="move();">&hearts;</div>
    </div>
    </div>

</body>
</html>

到目前为止感谢!

1 个答案:

答案 0 :(得分:0)

如果你需要它随着时间的推移而移动,那么就这样做。我不会为你做功课,但我会给你一个大纲,这样你就可以弄清楚如何编程:

- determine how many milliseconds MS you want the thing to move for (universal)
- determine the starting speed to move in (universal)
on mouseover:
  - determine the current object position (x,y)
  - determine the speed and direction of travel (dx,dy) for the object
  - record the mouseover start time for this object
  call update.

使用更新功能:

update:
  - determine the current acceleration A as: map "now" from (start,start+MS) to (1,0).
  - determine the object's new position (x + A*dx, y + A*dx)
  - update (x,y) to be these new values
  if (f > 0):
    schedule a next call to update some time in the future.

这是“不要立即开始编程&#34;在你坐下程序实际代码之前做的分析,因为这样,你现在知道代码的所有部分应该在你实现它们之前做什么,并且当事情没有发生时它会更容易被发现#39工作,因为你已经知道它应该如何运作。