'move something with javascript and make it moving slower
I've got a homework and cant solve it. We have to make a Heart moving in a random direction by mouseover. Like in real world it should then get slower in moving.
I tried to realize this with a setInterval, but I cant decrease the Interval and so it is not slowing down. Here is my code, maybe someone can help:
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();">♥</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();">♥</div>
</div>
</div>
</body>
</html>
Thanks so far!
Solution 1:[1]
If you need it to move over time, literally do that. I won't be doing your homework for you, but I will give you the outline so you can then figure out how to program that:
- 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.
with as update function:
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.
This is the kind of "don't immediately start programming" analysis you do before you sit down to program the actual code, because this way, you now know what all the bits of your code should do before you implement them, and it'll be much easier to spot when something doesn't work (because you already know how it's supposed to work at each step).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
