如何在Unity 3D中擲骰子

來源:互聯網
上載者:User

標籤:inpu   span   pre   sep   向量   答案   應用   螢幕   識別   

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 diceinitPos = Input.mousePosition; //return x component of dice from screen to view pointinitXpose = cam.ScreenToViewportPoint (Input.mousePosition).x;} //current position of mouseVector3 currentPos = Input.mousePosition; //get all position along with mouse pointer movementVector3 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 diceRollTheDice(newPos);//use identify face value on diceStartCoroutine(GetDiceCount ());} //Method Roll the Dicevoid 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 countvoid 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

 

 

如何在Unity 3D中擲骰子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.