...

View Full Version : Polar Coordinates



herbps10
05-05-2006, 02:34 AM
I am trying to make a simple script that when the html page is clicked, a div tag moves in a straight line to the place where you clicked. I'm doing so with polar coordinates and trigonometry. The problem is that when you click, the layer shoots thousands of pixels of the page in the general direction that was clicked.

I've already got the math to do the same thing in visual basic, so im pretty sure thats not the problem.

About the code,
via debugging I found that all of the code above the while loop is correct, and functions as it should. The problem arises in the while loop. I tried dividing I*stepsize*math.cos(theta) by some number to see if it was a units problem, but when I do, the layer goes to the same place about in the middle of the screen no matter where you click.

Any help would be greatly appreceated. :)

Heres the code:

function moveobj(x,y){
var theta;
var stepsize;
var deltax;
var deltay;
var n = 1;
var pi = 3.14159265357989;
var d;
var i;

var prex = document.getElementById("test").style.left;
var prey= document.getElementById("test").style.top;

var startx = prex.substring(0,prex.length-2);
var starty = prey.substring(0,prex.length-2);

d = Math.sqrt(Math.pow((x-startx),2) + Math.pow((y - starty),2));
deltax = x-startx;
deltay = y-starty;

stepsize=d/n;
if (deltax != 0) {
theta = Math.atan(deltay / deltax);
if (deltax < 0) {theta = theta + pi}
}
else {
if (deltax == 0) {
if (deltay < 0) {theta = -pi}
if (deltay > 0) {theta=pi}
}
}


i = 0;

while (i<=n){
i++;

xi = startx + i *(stepsize*Math.cos(theta));
yi = starty + i * (stepsize*Math.sin(theta));


xi= xi + "px"
yi = yi + "px"
document.getElementById("test").style.left= xi
document.getElementById("test").style.top = yi
}
}

Vladdy
05-05-2006, 03:31 AM
http://demos.klproductions.com/sandbox/htmlblockmove.html

jkd
05-05-2006, 03:57 AM
Trig is abused in this scenario. Yes, you can calculate arctan and then cos/sin of the angle between where you clicked and the top of the browser canvas... but why? It's just moving in a straight line to the point, right?

Thus if (x0,y0) is there the DIV is originally, and (x1,y1), you can easily just parameterize a line:


x(t) = (x1-x0)*t + x0
y(t) = (y1-y0)*t + y0

Then just let t vary from 0 to 1. Or in code:


function move(div, x1, y1) {
var x0 = parseInt(div.style.left);
var y0 = parseInt(div.style.top);
var x = function(t) { return (x1-x0)*t+x0 };
var y = function(t) { return (y1-y0)*t+y0 };

var t = 0;
var interval = setInterval(function() {
if (t >= 1) {
clearInterval(interval);
}
else {
t += 0.01;
div.style.left = x(t) + "px";
div.style.top = y(t) + "px";
}
}, 10);
}


You can fudge around with the interval value and the t-increment to make it faster/slower/smoother/choppier.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum