Search Unity

naming faces HELP!

Discussion in 'Scripting' started by composer27, Dec 2, 2010.

  1. composer27

    composer27

    Joined:
    Dec 2, 2010
    Posts:
    1
    Greetings to everyone,

    I am new to this, the creation of games, so my first game I wanted to do with the next target,,, 3 dice to win when given the same number to the front, the dice are cubes, I write because I do not know how to refer to the faces of the cube. how do I explain to unity,, which of the sides is 1 and which is number 6,,, I appreciate your help
     
  2. laurie

    laurie

    Joined:
    Aug 31, 2009
    Posts:
    638
    It would probably be easier to think in terms of orientation rather than named faces. Game objects have a 'neutral' orientation (where they are at zero rotation in all axes) and they have a 'forward' direction, which is constant relative to the object as it rotates. When the orientation changes, so does the direction of the forward vector.

    What does that mean? Assume you label the side of the die that is forward 1: if the object's forward vector points up in world space, 1 is the top face; if the forward vector points down, 1 is on the bottom so 6 must be the top face. Similarly, you have transform.right and transform.up vectors. For any given orientation of the die (assuming you roll them on a flat surface) exactly one of those vectors is going to be vertical (pointing up or down). Therefore, by testing which one is vertical and determining which way that one points (up or down), you can determine which face is showing upwards.

    In other words, you just need to compare any two of transform.forward/right/up against Vector3.up to determine which face of the die is showing. You can do those comparisons easily with a dot product (see Vector3.Dot()) -- if Vector3.Dot(Vector3.up, transform.forward) is equal to 1, the forward face is on top and the die shows 1; if Vector3.Dot(Vector3.up, transform.forward) is equal to -1, the forward face is down, so the back face is on top and the die shows 6; otherwise Vector3.Dot(Vector3.up, transform.forward) will be equal to 0.5, and you will need to use similar tests against transform.right and/or transform.up.

    In practice, rather than write 'if (Vector3.Dot(...,...) == 1)' you should write 'if (Vector3.Dot(...,...) > 0.9)' (i.e. test for 'larger than a number close to 1' or 'smaller than a number close to -1' rather than 'is equal to 1/-1), since floating point (non-integer) calculations tend to have very small inaccuracies, which can cause an == comparison to fail when you expect it to succeed.