0

I am implementing a 2D football game. For my pass algorithm, I calculate the slope between the passer and reciever with the equation m = (y2-y1)/(x2-x1)

In some conditions x2 and x1 are equal resulting in a divide by zero exception. What should I do in this case?

I did not ask this question on math.stackexchange.com because it's a programming question.

4

2 回答 2

4

Don't use the slope of a line for this sort of operation, for just the reason you have stumbled across. Use instead the angle of the line from passer to passee. Apply a little trigonometry. If that little trigonometry is beyond you, delete this question, do some work, then post again when you get stuck again.

EDIT

I suggest you use trigonometry for 2 reasons.

  1. Because the slope of a line between two points with the same x coordinate is indeterminate. Yes, you could, as the other answer suggests, fiddle around and make the slope a very large value when the x coordinates are the same, but it's an unnecessary compromise when trigonometry, which will produce an angle whatever the x and y coordinates, is available.
  2. Trigonometry will give you a natural interpretation of the value of the angle from passer to passee. A pass at an angle of 90 degrees (pi/2 radians, though I'm not sure many footballers or fans think of angles in radians during a match) means a cross-field pass (I'm assuming that your y-axis aligns with the long axis of your pitch), a pass at an angle of 180 degrees is a back pass, and so forth.
于 2012-07-26T11:04:07.027 回答
1

If you would like to skip the Trig application, you could check if(x1 != x2) //whatever math needs to be done

This way, if the x's are equal, you could set your own value for a "flat pass" in the else statement and never have to worry about a divide by zero exception again.

Good luck with whatever route you choose! (I would recommend using Trig if you have the time to learn it (if necessary))

于 2012-07-26T11:14:25.770 回答