Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  6] [ 5]  / answers: 1 / hits: 42974  / 13 Years ago, tue, may 3, 2011, 12:00:00

I'm writing a code to move a character in a browser game. I managed to get the pixels it must move per second both horizontally and vertically.



pxsecx is the number of pixels it must move horizontally per second
pxsecy is the same but vertically



Basically it should += them to the current horizontal and vertical position.



I need the loop to keep repeating itself every second until the element position meets the new position (newx).



This is as far as I have gone:



<body onmousedown=showCoords(event)>
<script type=text/javascript>
function showCoords(evt){
oldx = parseInt(document.getElementById(character).style.left);
oldy = parseInt(document.getElementById(character).style.top);

width = parseInt(document.getElementById(character).style.width);
height = parseInt(document.getElementById(character).style.height);

newx = evt.pageX - width/2;
newy = evt.pageY - height/2;

disx = newx - oldx;
disy = newy - oldy;

diag = parseInt(Math.sqrt(disx*disx + disy*disy));

speed = 50;

secs = diag/speed;

pxsecx = disx/secs;
pxsecy = disy/secs;

while(document.getElementById(character).style.left<newx)
{
document.getElementById(character).style.left += pxsecx;
document.getElementById(character).style.top += pxsecy;
}
}
</script>


Everything works until the while where I have no idea how to do make it work every second. I'm testing it here: http://chusmix.com/game/movechar.php



How do I make it repeat that once a second so it works?



thanks


More From » javascript

 Answers
5

JavaScript is primarily asynchronous, so you'll need to rewrite this a little. setTimeout executes a function after a certain amount of time. Therefore, you can do this:



(function move() {
var character=document.getElementById(character);
if(character.style.left<newx) {
character.style.left += pxsecx;
character.style.top += pxsecy;
setTimeout(move, 1000);
}
})();

[#92441] Saturday, April 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiasavannahw

Total Points: 448
Total Questions: 122
Total Answers: 113

Location: Maldives
Member since Tue, Dec 21, 2021
3 Years ago
tiasavannahw questions
Sun, Oct 11, 20, 00:00, 4 Years ago
Sat, Aug 29, 20, 00:00, 4 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Mon, Mar 23, 20, 00:00, 4 Years ago
;