1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

This is a web page object.

Web Page Animation

13. Moving Diagonally

clr gif

So far we have made our object move horizontally or vertically. The next step is to get our object to move both horizontally and vertically at the same time. The easiest angle to code for is 45 degrees or diagonally. Since the angle is specified we will only need to test the end position in one direction to determine where to stop.

Since we are now going to be moving in two dimensions instead of one let's start by defining the step size for both directions. At the moment they will both be the same but doing this will make it easier to amend the script to handle any angle and not just 45 degrees.

var xxx = 0; var yyy = 0;
var startpos = endPos = 0;
var stepx = 2;
var stepy = 2;

Next we amend the start function to substitute the step size into the start and end position calculations in place of the hard coded number we used before.

function start() {
var w = objWidth('myobj');
xxx = (pageWidth()-w-20);
startPos = yyy = 10;
endPos = (pageHeight()-objHeight('myobj'))/2;
endPos -= (endPos-startPos) % stepy;

The only other piece of code that we need to change is the mover function which now has to adjust the location of our object in two dimensions. Since we are starting our object in the top right corner the x coordinate will decrease as the y coordinate increases and vice versa.

function mover() {
if (yyy < endPos) {
xxx -= stepx;
yyy += stepy;}
else if (yyy > endPos) {
xxx += stepx;
yyy -=stepy;}
else {endPos = startPos; startPos = yyy;}
moveit(); setTimeout('mover()',25);

Our object will now move diagonally starting from the top right corner of the screen and will move down until it is vertically centred in the window. It will have moved as far to the left as it will have moved down and so unless our window is exactly square (which is unlikely) the object will not be centred horizontally at the time that it reverses direction and moves back to the top right of the screen.

If you start the object from the top left corner of the screen or bottom right corner of the screen then both the x and y coordinates will increase or decrease together. Starting from the bottom left corner of the screen will be similar to starting from the top right but with the end position in the opposite direction relative to the start position.

See More About

©2017 About.com. All rights reserved.