Undoubtedly this question has been asked before, except I completely lack the knowledge to find it.
I'm trying to write the classic snake (aka Nibbles) game and the logic is pretty straight forward. Direction is expressed by a delta coordinate pair. North is -1, 0; east is 0, 1; south is 1,0; and west is 0, -1.
It's been a decade since I took a math course so I'm not exactly sure how to convert those pairs into something where North = 0 degree's; east = 45, south = 90; and west = 135 in which case the problem is drastically simple and becomes a case of clock arithmetic then conversion back to delta pairs.
Also, this is not academic homework but self-education
Edit: Got a working prototype thanks to the selected answer below. http://ominian.com/examples/js/pinglib/snakes.html
If you really mean degrees then you want increments of 90 degrees rather than 45.
You need the
atan2
function (which exists in various forms in many languages). Something likeangle = 180/pi * atan2(dy,dx)
-- the180/pi
is becauseatan2
returns a value in radians. There will be numerous small mismatches between what this does and what you want:dy
will be taken to increase upwards rather than downwards, 0 will be east rather than north, andatan2
typically returns values between -pi and +pi rather than between 0 and 2pi. Untangling all these is left as an exercise for the reader :-).If you only need the 4 special cases you described then you could do something ugly and ad hoc. For instance,
angle = 180*(dy-dx>0)+90*(dx!=0)
will do the job because S,W share the property thatdy-dx>0
and E,W share the property thatdx!=0
.You may well find it better to work with
dx,dy
values everywhere and not use angles explicitly at all. For instance, rotation through 90 degrees is just(dx,dy)=(-dy,dx)
(or(dy,-dx)
for the other direction).
The function you want is atan2() - arctangent of two arguments. It is there specifically for that purpose. It returns a result in radians, of course, so you will have to convert to degrees, and it returns a result relative to conventional angles, where zero is along the +X axis, and +pi/2 is along the +Y axis, so you will have to convert to heading angles.
Most languages have an atan2 function which will directly convert x,y deltas into an angle in radians. It's up to you to convert it into degrees.
精彩评论