开发者

Conversion of a delta pair to degree's [closed]

开发者 https://www.devze.com 2023-02-19 19:43 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_StackOverflow社区 Closed 11 years ago.

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


  1. If you really mean degrees then you want increments of 90 degrees rather than 45.

  2. You need the atan2 function (which exists in various forms in many languages). Something like angle = 180/pi * atan2(dy,dx) -- the 180/pi is because atan2 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, and atan2 typically returns values between -pi and +pi rather than between 0 and 2pi. Untangling all these is left as an exercise for the reader :-).

  3. 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 that dy-dx>0 and E,W share the property that dx!=0.

  4. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消