如何在Unity 3D中掷骰子

1、介绍
2、滚一个骰子
3、导入模型
4、添加脚本
5、方法
6、识别骰子上的随机面值
 
客观的
这篇文章的主要目的是给你一个关于如何在Unity 3D中掷骰子的想法。
 
第一步介绍
1、构建一个棋盘游戏,但对骰子有问题;这里是一个示例代码,演示如何像真正的骰子一样掷骰子,以及如何在游戏控2、制台上识别骰子的表面值。
3、这个问题分为两个主要部分:
4、如何掷骰子?
5、确定在1和6之间的随机整数(6个标准骰子)的面值。
第二步掷骰子
 
2.1导入模型
将一个标准骰子模型导入到unity3D中。调整转换,如图所示,并将刚体添加到它。
 
2.2添加脚本
现在将代码片段添加到脚本中。
请注意
这段代码可以让你滚动骰子,就像你用鼠标在屏幕上滑动一样,如果你做出了适当的改变,你可以很容易地为触摸设备转化。
if (Input.GetMouseButtonDown (0))
{
//initial click to roll a dice
initPos = Input.mousePosition;
 
//return x component of dice from screen to view point
initXpose = cam.ScreenToViewportPoint (Input.mousePosition).x;
}
 
//current position of mouse
Vector3 currentPos = Input.mousePosition;
 
//get all position along with mouse pointer movement
Vector3 newPos = cam.ScreenToWorldPoint (newVector3(currentPos.x,currentPos.y,Mathf.Clamp(currentPos.y/10,10,50)));
 
//translate from screen to world coordinates  
newPos = cam.ScreenToWorldPoint (currentPos);
 
if (Input.GetMouseButtonUp (0))
{
initPos = cam.ScreenToWorldPoint (initPos);
 
//Method use to roll the dice
RollTheDice(newPos);
//use identify face value on dice
StartCoroutine(GetDiceCount ());
}
 
//Method Roll the Dice
void RollTheDice(Vector3 lastPos)
{
               diceObject.rigidbody.AddTorque(Vector3.Cross(lastPos, initPos) * 1000, orceMode.Impulse);
lastPos.y += 12;
diceObject.rigidbody.AddForce (((lastPos - initPos).normalized) * (Vector3.Distance (lastPos, initPos)) * 25 * duceObject.rigidbody.mass);
}
2.3方法

这就是投掷骰子方法的工作原理:

最初,在掷骰子时,增加扭矩来旋转骰子。它的外观和感觉就像真正的骰子滚动了一样。

使用lastPos和initPos的交叉乘积来计算转矩量,就像真正的骰子和鼠标移动的方向一样。

同样的力被添加到向鼠标的方向投掷骰子。
//Coroutine to get dice count
void GetDiceCount()
{
if (Vector3.Dot (transform.forward, Vector3.up) > 1)
diceCount = 5;
if (Vector3.Dot (-transform.forward, Vector3.up) > 1)
diceCount = 2;
if (Vector3.Dot (transform.up, Vector3.up) > 1)
diceCount = 3;
if (Vector3.Dot (-transform.up, Vector3.up) >1)
diceCount = 4;
if (Vector3.Dot (transform.right, Vector3.up) >1)
diceCount = 6;
if (Vector3.Dot (-transform.right, Vector3.up) >1)
diceCount = 1;
Debug.Log ("diceCount :" + diceCount);
}
第三步确定骰子的随机面值
上面的代码片段解释了如何识别骰子上的随机面值。
这个代码片段必须包含在脚本中,该脚本应用于层次结构中的骰子,而转换应该如图1所示。
点积是用来发现要考虑哪个面的。
另外,如果梯子被用来评估不同的骰子和矢量之间的点积的结果。向上和结果与1相比(意味着骰子和矢量3。向上是平行的,这确实是需要的答案)
我希望你在Unity 3D的时候发现这个博客很有帮助。如果你有任何关于Unity 3D的问题或问题,请在这里发表评论,我们会尽快回复你。
原文链接:http://www.theappguruz.com/blog/roll-a-dice-unity-3d

 

 
posted @ 2017-05-31 16:49  IT1990  阅读(4562)  评论(2编辑  收藏  举报