...

View Full Version : setTimout not working for animation, please help!



Emancip8
04-22-2008, 02:12 PM
I have been trying to recreate the breakout game using javascript as a uni project. I have been able to get animation to work a certain way but not the way i have been asked to do it which is annoying.
I have he following code:


var lives = 2;
var score = 0;
var ball;
var position;
var direction;

function initialize()
{
document.getElementById('lives').innerHTML = "Lives: " + lives;
document.getElementById('score').innerHTML = "Score: " + score;
ball = new object();
direction = "north";
}

function object()
{
this.move = move;

function move()
{
var style = document.getElementById('ball');

if (direction == "north")
{
position = parseInt(style.style.top);
if (position > 0)
{
position = position - 2;
setTimeout('move()', 10);
style.style.top = position;
}
else
{
direction = "south"
collide();
}
}
if (direction == "south")
{
position = parseInt(style.style.top);
if (position < 287)
{
position = position + 2;
setTimeout('move()', 10);
style.style.top = position;
}
else
{
direction = "north";
collide();
}
}
}
}

function collide()
{
if (direction == "north")
{
bounce("north");
}
}

function bounce(dir)
{
if (dir == "north")
{
direction = "north";
move();
}
}
I got it working by using:
style = document.getElementById('ball').style - inside the move() function, but i have been asked to define ball as an object with methods. The code above only moves the ball 2 pixels when i call ball.move() so is it the setTimeOut that needs changing? Any help would certainly be very much appreciated :confused:
Here's the markup:

<body onload = "initialize()">
<hr/>
<h1>Javascript Game</h1>
<hr/>
<a href = "#">Home</a>
<p/>
<form>
<div id = "gameBoard">
<div id = "boundary">
<div id = "ball"style = "left: 202.5px; right: 207.5; top: 287.5px; bottom: 292.5;"></div>
<div id = "paddle"></div>
</div>
<div id = "gameControl">
<div id = gameTitle>Breakout
Game</div>
<div id = "lives"></div>
<div id = "score"></div>
<input type = "button" value = "Start" id = "buttonStart" onclick = "ball.move()">
<br>
<input type = "button" value = "Stop" id = "buttonStop">
<br>
<input type = "button" value = "End Game" id = "buttonEnd">
<br>
</div>
</div>
</form>
</body>

mjlorbet
04-22-2008, 02:20 PM
in your move function, before the setTimeout add
var me = this; and change "move()" in setTimeout to me.move (no parenthesis, we're looking for the function reference)

Kor
04-22-2008, 02:49 PM
Emancip8, please don't cross post. You have the same question here:
http://www.codingforums.com/showthread.php?t=138130

Emancip8
04-22-2008, 03:00 PM
mjlorbet that worked beautifully, thankyou so much
:thumbsup::)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum