如果在 unity中滚动 3D 骰子

发表于2017-10-16
评论0 3.2k浏览

骰子这个在游戏开发中算一个比较不起眼的功能,但是实现起来却并不那么容易,下面这个文章要和大家介绍的是在Unity中滚动 3D 骰子,想知道实现方法的可以看看。 


创建一个棋盘游戏   但因为骰子困扰,这个问题分为两个主要部分:

       1.如何掷骰子。

       2.确定是 1和6之间的随机一个整数面值 (六面临标准骰子)。 


如何掷骰子 

步骤-1:   将标准骰子模型导入 unity3D。调整Transform ,如图所示,将 刚体添加到它。



步骤 -2:  现在将代码片段添加 到脚本 。

           注: 这段代码使您能够使用鼠标触发 ,如果进行适当更改,你可以轻松地变为触摸设备。 

  1. if (Input.GetMouseButtonDown (0))  
  2. {  
  3. //initial click to roll a dice  
  4. initPos = Input.mousePosition;  
  5.    
  6. //return x component of dice from screen to view point  
  7. initXpose = cam.ScreenToViewportPoint (Input.mousePosition).x;  
  8. }  
  9.    
  10. //current position of mouse  
  11. Vector3 currentPos = Input.mousePosition;  
  12.    
  13. //get all position along with mouse pointer movement  
  14. Vector3 newPos = cam.ScreenToWorldPoint (newVector3(currentPos.x,currentPos.y,Mathf.Clamp(currentPos.y/10,10,50)));  
  15.    
  16. //translate from screen to world coordinates    
  17. newPos = cam.ScreenToWorldPoint (currentPos);  
  18.    
  19. if (Input.GetMouseButtonUp (0))  
  20. {  
  21. initPos = cam.ScreenToWorldPoint (initPos);  
  22.    
  23. //Method use to roll the dice  
  24. RollTheDice(newPos);  
  25. //use identify face value on dice  
  26. StartCoroutine(GetDiceCount ());  
  27. }  
  28.    
  29. //Method Roll the Dice  
  30. void RollTheDice(Vector3 lastPos)  
  31. {  
  32.                diceObject.rigidbody.AddTorque(Vector3.Cross(lastPos, initPos) * 1000, orceMode.Impulse);  
  33. lastPos.y  = 12;  
  34. diceObject.rigidbody.AddForce (((lastPos - initPos).normalized) * (Vector3.Distance (lastPos, initPos)) * 25 * duceObject.rigidbody.mass);  
  35. }  

步骤-3:  RollTheDice 方法是如何工作的:

        最初,掷骰子时 扭矩Torque 被添加 旋转骰子。然后 力Force 被增加, 所以它会给真正的骰子被滚动的外观和感觉。

        转矩的计算使用 交叉产品的 lastPos 和 initPos 对移动旋转像真正的骰子,并将在鼠标的方向移动 。

同样添加力Force ,以掷骰子的鼠标的方向。 

  1. //Coroutine to get dice count  
  2. void GetDiceCount()  
  3. {  
  4. if (Vector3.Dot (transform.forward, Vector3.up) > 1)  
  5. diceCount = 5;  
  6. if (Vector3.Dot (-transform.forward, Vector3.up) > 1)  
  7. diceCount = 2;  
  8. if (Vector3.Dot (transform.up, Vector3.up) > 1)  
  9. diceCount = 3;  
  10. if (Vector3.Dot (-transform.up, Vector3.up) >1)  
  11. diceCount = 4;  
  12. if (Vector3.Dot (transform.right, Vector3.up) >1)  
  13. diceCount = 6;  
  14. if (Vector3.Dot (-transform.right, Vector3.up) >1)  
  15. diceCount = 1;  
  16. Debug.Log ("diceCount :"   diceCount);  
  17. }  

步骤-4:  以上代码段说明如何确定在骰子上随机的面值。

        这段代码必须包含在脚本中,  骰子在hierarchy和transforms 应该是如图 1 所示。

       点数用于查找哪一张脸是将被考虑。


通过以上这四个步骤,基本在Unity中滚动 3D 骰子就可以实现出来了,掌握方法后还是比较容易的吧。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

标签:

0个评论