IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]如果在 unity中滚动 3D 骰子

    u010019717发表于 2015-08-26 08:21:31
    love 0

    孙广东   2015.8.16


    目的:     这篇文章的主要目的是为了让您了解有关如果在 unity中滚动 3D 骰子  

                  建设一个棋盘游戏   但因为骰子困扰   ;  

           这个问题分为两个主要部分:

            如何掷骰子。

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

    如何掷骰子 

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



    步骤 -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);
    }

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

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

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

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


    //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);
    }

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

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

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






沪ICP备19023445号-2号
友情链接