Page 1 of 1

Good at Math?

Posted: Mon Jan 05, 2004 12:01 am
by Gen-ik
I hope someone out there is better at Math than I am because I'm stuck with something :roll:

What I'm trying to find out is how to get an angle between two points using JavaScript. For example if PointA was at 100x,100y and PointB was at 150x,200y what would the angle be (0,30,90,180,270 etc).

If you could help out that would be great.

Just as a quick reminder JavaScript can use all of the usual Math functions such as acos, atan, ceil, cos, exp, floor, max, min, pow, round, sin, sqrt... and so on.

Posted: Mon Jan 05, 2004 2:00 am
by volka
the angle between two vectors is given by cross product / product of lengths

Code: Select all

<html>
	<head>
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			function angle(x1, y1, x2, y2)
			&#123;
				var vecprod = x1*x2 + y1*y2;
				var vecabs = Math.sqrt(x1*x1 + y1*y1) + Math.sqrt(x2*x2 + y2*y2);
				var a = vecprod / vecabs;
				return Math.acos(a);
			&#125;
			document.write(angle(0, 1, 1, 0));
		</script>
	</body>
</html>
the return value is in pi
so document.write(angle(0, 1, 1, 0)); writes 1.57...

Posted: Thu Jan 08, 2004 1:24 pm
by Gen-ik
Ok here's another one to keep those brains cells buring.

I'm trying to find the quickest (less processor intensive) way of checking if an object has crossed a line... a box hitting a wall for example.

I'm working with two points (POINT(A) and POINT(B)) which represent either end of the line, or wall.

Here's a little piccy...
Image


The method I'm using at the moment isn't very acurate (lots of guestimating going on) and I'm hoping there's a more accurate mathimatical way of doing it..... please tell me there's an easier way of doing it :?

Posted: Thu Jan 08, 2004 3:59 pm
by toms100
well... you could create a formula for the hypotanus of the line, then equate mathmatically to the box... but that would be complicated

Posted: Fri Jan 09, 2004 8:14 am
by Gen-ik
toms100 wrote:well... you could create a formula for the hypotanus of the line, then equate mathmatically to the box... but that would be complicated
Hmm, sounds interesting.
I've currently got my own functions together which are working out positions/field of depth/rotation etc for objects (points) in a 3D space, so adding a bit more complexity to it might not be too much of a headache.

Do you have any examples?

Posted: Sat Jan 10, 2004 9:24 am
by uberpolak
Trigonometry and its hyperactive cousin calculus are satanic tools of mass frustration. A pox upon them both.