zoukankan      html  css  js  c++  java
  • Unity3d中CharacterController的移动和碰撞分析

    在Unity3d中系统提供的第一人称视角模型First Person Controller的移动可分为两种:

    一.移动transform

      这种移动方式为直接对该人物模型的transform属性做位移操作,移动方式为在Update函数中的写法:

    void Update () {
         if(Input.GetKey(KeyCode.W))
         {
            transform.Translate(Vector3.forward * Time.deltaTime * speed);
         }
         else if(Input.GetKey(KeyCode.S))
         {
            transform.Translate(Vector3.forward * Time.deltaTime * -speed);
         }
         else if(Input.GetKey(KeyCode.A))
         {
            transform.Translate(Vector3.right * Time.deltaTime * -speed);
         }
         else if(Input .GetKey(KeyCode.D))
         {
           transform.Translate(Vector3.right * Time.deltaTime * speed);
         }
    }

      人物模型的碰撞检测:

    1.这种方法不会触发静态碰撞,即在静态碰撞器的物体中可以穿进,穿出。

    2.在碰撞带有刚体组件的物体时能够发生刚体碰撞,若要检测刚体碰撞,必须将检测脚本附加在带刚体组件的物体上。

    3.人物模型可以进行触发器检测。

    二:利用系统提供的人物模型类CharacterController对象中的Move方法进行移动,具体代码如下:

    CharacterController controller;
    
    controller.Move(Vector3.forward * Time.deltaTime * speed);

     人物模型的碰撞检测:

    1.这种移动方法的人物模型在静态碰撞器中可以发生静态碰撞,即不能够穿越物体,碰到有静态碰撞器的物体只能停下来。

    2.在碰撞带刚体的物体时,不会穿越该物体,也不会触发任何的刚体碰撞检测函数,但是可以用另外一个函数用来检测人物模型接触到刚体物体。

    检测函数举例:

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Rigidbody body = hit.collider.attachedRigidbody;
        if(body == null || body.isKinematic)
        {
            return;
        }
        else
        {
            Debug.Log("touch gameObject: " + hit.collider.gameObject.name);
                    
            //摧毁物体
            //Destroy(hit.collider.gameObject);
            
            //给物体一个移动的力
           //body.velocity = new Vector3(hit.moveDirection.x,0,hit.moveDirection.z) * 30.0f;
        }
    }        

     3.这种移动方法也能执行触发器检测函数。

  • 相关阅读:
    BNUOJ 12756 Social Holidaying(二分匹配)
    HDU 1114 Piggy-Bank(完全背包)
    HDU 2844 Coins (多重背包)
    HDU 2602 Bone Collector(01背包)
    HDU 1171 Big Event in HDU(01背包)
    HDU 2571 命运 (入门dp)
    HDU 1069 Monkey and Banana(最长递减子序列)
    HDU 1160 FatMouse's Speed (最长上升子序列)
    HDU 2594 KMP
    POJ 3783 Balls --扔鸡蛋问题 经典DP
  • 原文地址:https://www.cnblogs.com/csdnmc/p/4223480.html
Copyright © 2011-2022 走看看