Hi there, I am reading a javascript book and I got a little stuck when analysing one of the scripts built as test. This is the one I am talking about http://aharrisbooks.net/jad/chap_08/bounce.html
I went through it but I don’t seem to be able to understandexactly the way it works.
Here’s the code.
html:
view-source:http://aharrisbooks.net/jad/chap_08/bounce.html
movement.js:
http://aharrisbooks.net/jad/chap_08/movement.js
bounce.js
http://aharrisbooks.net/jad/chap_08/bounce.js
Let’s see if I understand it correctly.
The <body onload = "init()">
in the html file calls the init()
function in bounce.js because if you duplicate a function, the browser interprets only the last one it reads and in fact there is another init()
function in movement.js which the script skips.
So in bounce.js the function init()
calls animate()
is called once every 0.05 seconds. Animate()
calls moveSprite(deltaX, deltaY)
. This function is contained in movement.js, so let’s just do a few rounds.
DeltaX and DeltaY are respectively 5 and 3, so the first run is moveSprite(5, 3)
. As per the code in movement.js before checkBounds()
is called - incidentally checkBounds()
will call the function in bounce.js and not the one in movement.js - x = 105 and y =103 so we change the left and top values the sprite moves to that position. So far so good.
Now let’s run the function one last time, to see how the ball bounces back. Say that x = 365 now. So, Animate()
calls moveSprite(deltaX, deltaY)
, we run
x = parseInt(sprite.style.left);
y = parseInt(sprite.style.top);
x += dx;
y += dy;
and x, which is 365 should becomes 370 (365+5). checkBounds()
is called and x>MAX_X
is true – assume all the other conditions are false - so deltaX = -5. Control returns here
sprite.style.left = x + "px";
sprite.style.top = y + "px";
but x is still 370 so the left value is 370px?! I just don’t get how x becomes 365 again (370-5)
I got a little lost...