# Calculate Slope of a Line

Actionscript:
1. // calculate the slope of a line
2. function calculateSlope(x1:Number, y1:Number, x2:Number, y2:Number):Number {
3.         // rise over run
4.     var s:Number = (y1 - y2) / (x1 - x2);
5.     /*if (x1==x2) {
6.         // slope is Infinity or -Infinity
7.     }*/
8.     return s;
9. }
10.
11. /**
12.  Test it out
13. */
14. function draw(x1:Number, y1:Number, x2:Number, y2:Number):void {
15.     graphics.moveTo(x1, y1);
16.     graphics.lineTo(x2, y2)
18.     txt.text = calculateSlope(x1, y1, x2, y2).toFixed(2);
19.     txt.x = x2, txt.y = y2;
20. }
21.
22. graphics.lineStyle(0,0xFF0000);
23. draw (100, 100, 200, 200);
24.
25. draw(100, 100, 200, 150);
26.
27. draw(100, 100, 200, 100);
28.
29. draw(100, 100, 99, 200);

This snippet shows how to calculate the slope of a line ... It demos the function by drawing a few lines and showing the corresponding slope of each.

It will draw this: If (x1 == x2), the slope will be -Infinity or Infinity... depending on where you're using this calculation you may want to reset the s variable to something else, return null etc... I commented it out for simplicity.

• 