Search Unity

[c#] Using a vector3 in a switch statement

Discussion in 'Scripting' started by kevdotbadger, Mar 3, 2013.

  1. kevdotbadger

    kevdotbadger

    Joined:
    Sep 13, 2011
    Posts:
    82
    Hello, i'm looking for a way to determine which way my character is pointing (north, north_east, east, etc).

    I have a load of if statements to do this at the moment, but it's messy. It also seems that i cannot use a Vector3 in the switch statement.

    Any idea's how I would do this?

    Here's how it looks presently

     
    Last edited: Mar 3, 2013
  2. vagos21

    vagos21

    Joined:
    Sep 3, 2012
    Posts:
    18
    How about reading the Y rotation of your object and then do an integer division of the angle by let's say...45 (each direction changes per 45 degrees) and then use that result in a case to determine which direction it's facing?

    so for example let's say your gameobject's (world) Y rotation is at 240degrees, 240/45=5

    and the cases would be like
    0 north
    1 northeast
    2 east
    3 southeast
    4 south
    5 southwest
    6 west
    7 northwest

    just giving hints :)
     
    Last edited: Mar 4, 2013
  3. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,130
    switch works fine with a V3, but be aware, when you check for V3 == V3 it checks for EXACTLY the same,
    so V3(1, 0.0001, 0) is never the same as V3(1, 0, 0)
    and doing checks with values calculated from velocity and so on will nearly always have floating decimal values
     
  4. scarpelius

    scarpelius

    Joined:
    Aug 19, 2007
    Posts:
    954
  5. kevdotbadger

    kevdotbadger

    Joined:
    Sep 13, 2011
    Posts:
    82
    Hello, thanks for the input. My game is a 2d top down game, so I was managing the direction they are looking at to determine what animation i should be playing.

    So I don't think using Vector3.Angle() would work.
     
  6. Annihlator

    Annihlator

    Joined:
    Oct 15, 2012
    Posts:
    378
    Ofcourse Vector3.Angle() still works, your game may be displayed in 2d, but unity's worldspace is also fully 3d. your third dimension is just "flat".
    However for calculating angles for Vector2's, i found this topic in Unity Answers you may be interested in, too. (even though this seems to be a C# implementation instead of Java.) http://answers.unity3d.com/questions/162177/vector2angles-direction.html
    Scarpelius' method should work fine too though!
     
  7. kevdotbadger

    kevdotbadger

    Joined:
    Sep 13, 2011
    Posts:
    82
    Thanks guys, both answer contained excellent advice and using the link from Annihlator's post I was able to set this up like I wanted. Also learnt about the Vector3.Cross() method.
     
unityunity