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.

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.