Take the 2-minute tour ×

Possible Duplicate:
How do I calculate the angle of the slope at a point on a 2D bitmap terrain?

I am planning to make a platform game with my own little engine and I need to know how to detect the angle of a slope. Any help is appreciated.

share|improve this question

marked as duplicate by Byte56, Josh Petrie, Sean Middleditch, Nathan Reed, Arcane Engineer Dec 30 '12 at 20:38


2 Answers 2

You need to know 2 points to calculate a slope, in this example you have p1 and p2 as the two points. You use the Pythagorean theorem to calculate it.

// Delta X and Y
dx = p1.x - p2.x;
dy = p1.y - p2.y;

// Calculate the angle
slope = Math.atan2(dy,dx);

// Convert the angle to degrees
slope = slope * 180 / Math.PI;
share|improve this answer
While your algorithm is correct, it does not make use of the Pythagorean theorem (nor does it need to). You're using the arctangent as it was intended to be used. –  chaosTechnician Dec 27 '12 at 17:21
Thanks, but I also need to know how I would get p1 and p2 –  Chaquator Dec 27 '12 at 19:09

You have two options, and it depends on how you plan to go about your game's collision detection.

If the collision data for your levels can be represented as line segments (or other shapes that can be broken down into line segments), you can use atan2 to find the angle between the endpoints of each line segment as suggested by Thomas.

If your game is tile-based, each tile would likely hold collision data that you've created manually. (E.g. tile type, angle of slope, etc.)

share|improve this answer
