- Home /

**closed**Dec 04, 2014 at 04:52 AM by Prasanna for the following reason:

The question is answered, right answer was accepted

# Dice Value

Hello there,

I have code for calculating dice value... they using dot product to get the value, i want to know about the code. if anyone know about dot product pls explain me or anyone know how to calculate the dice value tell me the logic. Here is the code.

```
using UnityEngine;
using System.Collections;
public class DiceValue : MonoBehaviour
{
public int side=0;
int CalcSideUp()
{
float dotFwd = Vector3.Dot(transform.forward, Vector3.up);
if (dotFwd > 0.99f) return 7;
if (dotFwd < -0.99f) return 4;
float dotRight = Vector3.Dot(transform.right, Vector3.up);
if (dotRight > 0.99f) return 8;
if (dotRight < -0.99f) return 3;
float dotUp = Vector3.Dot(transform.up, Vector3.up);
if (dotUp > 0.99f) return 5;
if (dotUp < -0.99f) return 2;
return 0;
}
void Update()
{
int side = CalcSideUp();
if (side > 0)
{
Debug.Log("Side = " + side);
}
}
}
```

-Prasanna.

**Answer** by robertbu
·
Feb 11, 2014 at 06:27 AM

This code is using the dot product in a very specific way. What they are doing only works if all the vectors involved are normalized (i.e. of unit length). All the ones they are use are normalized. When two normalized vectors are pointing in the same direction, their dot product value will be 1.0 (give or take a bit due to floating point imprecision). If two vectors are pointing in opposite directions, then dot product will be -1.

The other thing going on here is the value of each side of the cube. Their cube has the following values:

front - 7

back - 4

right - 8

left - 3

top - 5

bottom - 2

So take a look at lines 9 - 11. First the forward vector is compared with world up. If they are the same (i.e. dotFwd > 0.99f), then you know the forward side is facing up. If the value is near -1, then you know the back side is facing up.

Lines 13-15 text left/right.

Lines 17-19 test top bottom.

In the unlikely event the cube is on the edge (i.e. it got hung up on something), the function returns 0.

### Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.