Web Page Animation15. Random Movement |
|
Join the DiscussionWe could easily get our script to move from its start position to any randomly chosen spot on the screen just by substituting the code from the random start position script of tutorial four for our currently defined end position of the exact centre of the browser window. Instead of having the object return to its start position though, let's make it a bit more interesting by having the script select a new random end position and continue on toward that. The effect should be that our object will now move randomly around the screen travelling in a straight line from one randomly selected point to the next. First we need to extract some of the code from our start function into a new function that will select a new random end position (only the changes from the extracted code are shown in bold):
function nextEnd() {
var eX = Math.floor(Math.random()* (pageWidth()-objWidth('myobj'))); var eY = Math.floor(Math.random()* (pageHeight()-objHeight('myobj'))); dist = distX = distance(xxx,eX); distY = distance(yyy,eY); stepx = 2 * direction(xxx,eX) * rate(distX,distY); stepy = 2 * direction(yyy,eY) * rate(distY,distX); stepy *= direction(yyy,eY) * rate(distY,distX); } Next we replace that code within the start function with a call to our new function:
function start() {
var w = objWidth('myobj'); xxx = (pageWidth()-w-20); yyy = 10; nextEnd(); moveit(); setObjVis('myobj','visible'); mover(); } The final change is to call that same function again from the mover function to set a new random destination when the previous one is reached.
function mover() {
if (dist > 0) { xxx += stepx; yyy += stepy; dist -= Math.abs(stepx);} else {nextEnd();} moveit(); setTimeout('mover()',25); } |

