4
\$\begingroup\$

I am making a snake game. I want to rotate my snake in the direction specified by swiping on the screen, the directions are limited to orthogonals (90 degree increments). It's an android game.

Can someone provide me with an algorithm to rotate a snake given its current rotation, and a swipe direction? As it rotates at 90 degrees correctly but not always in the direction specified by swipe.

enter image description here

\$\endgroup\$
  • 1
    \$\begingroup\$ What do you want to do? Do you want the snake's direction to rotate so that it as closely as possible matches the movement of the swipe, given the 90 degree steps? \$\endgroup\$ – Herp Mar 27 '14 at 14:02
  • 2
    \$\begingroup\$ Nice screenshot but where's your code? \$\endgroup\$ – Thomas Mar 27 '14 at 14:17
  • 1
    \$\begingroup\$ I will try and help you, but you need to explain better exactly what you want to do. Do you have the start and end points of the swipe? \$\endgroup\$ – Herp Mar 27 '14 at 14:19
  • \$\begingroup\$ Herp. I am using this code . transform.Rotate(new Vector3(0, 90, 0)); Inside my update method, when a swipe right is detected. for swipe left I changed 90 to -90 . but for up and down, I don't know what to do :( \$\endgroup\$ – Adnan Nazir Mar 27 '14 at 14:25
  • 2
    \$\begingroup\$ No problem, answer your own question in case somebody else runs into this problem. \$\endgroup\$ – Herp Apr 1 '14 at 7:18
0
\$\begingroup\$

You cannot use transform.Rotate because that will always rotate relative to whichever direction is currently facing. What you want to use instead is Transform.eulerAngles which will explicitly set a rotation despite whatever the current rotation is:

transform.eulerAngles = new Vector3(0f, yAngleRotation, 0f); Each swipe direction would have a different yAngleRotation value (I'm not sure exactly which as it depends on what axis and direction your game is on / displayed at). These values would probably each be 0f, 90f, 180f, 270f.

One key thing to note is to make sure you don't just set one axis rotation by itself or you will get bad results... as in don't do this:

// this is very very bad, don't do this!!! transform.eulerAngles.y = yAngleRotation;

Thanks to Leuthil from unity3d forum Who solve my problem. Thanks allot :) all of the others who sincerly tried for me.

\$\endgroup\$
  • 3
    \$\begingroup\$ Actually you can use transform.Rotate. Just use the version of the method that defines the Space you want to rotate relative to. \$\endgroup\$ – MichaelHouse Apr 1 '14 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.