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