- Home /
Question by
saremi-alireza · May 16, 2020 at 07:47 AM ·
collision detectiondice
detect cube face based on a random number
I've created a random number between 1 to 6. How can I show a cube side based on generated number. Actually this is a 3D dice but I want to generate dice value before tossing dice. Any Idea would help me. thanks.
Comment
Answer by saremi-alireza · May 16, 2020 at 08:56 AM
I found a solution but I am not sure this is the best.
First I've added a tiny sphere for each side of my dice add turn off mesh renderer to disappear that.
then add this script to generate random number and rotate the dice according to generated dice value.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dice2 : MonoBehaviour
{
private Rigidbody rigidbody;
private Vector3 initPosition;
private Transform theDice;
void Start()
{
rigidbody = GetComponent<Rigidbody>();
initPosition = transform.position;
rigidbody.useGravity = false;
theDice = this.transform;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
RollTheDice();
}
else if (Input.GetKeyDown(KeyCode.Backspace))
{
ResetTheDice();
}
}
private void RollTheDice()
{
int diceValue = UnityEngine.Random.Range(1, 7);
Debug.Log(diceValue);
switch (diceValue)
{
case 1:
theDice.localRotation = Quaternion.Euler(180, 0, 0);
break;
case 2:
theDice.localRotation = Quaternion.Euler(-90, 0, 0);
break;
case 3:
theDice.localRotation = Quaternion.Euler(0, 0, 0);
break;
case 4:
theDice.localRotation = Quaternion.Euler(90, 0, 0);
break;
case 5:
theDice.localRotation = Quaternion.Euler(0, 0, 90);
break;
case 6:
theDice.localRotation = Quaternion.Euler(0, 0, -90);
break;
default:
theDice.localRotation = Quaternion.Euler(45, 45, 45);
break;
}
rigidbody.useGravity = true;
}
private void ResetTheDice()
{
this.transform.position = initPosition;
rigidbody.useGravity = false;
}
}
screenshot-2.png
(112.1 kB)