unity学习之射线、角色控制器

来源:互联网 发布:js如何调用php函数 编辑:程序博客网 时间:2024/04/28 12:26
unity学习,希望我的博客能给喜欢unity的朋友带来帮助

角色控制器(character  controller

          角色控制器允许你在受制于碰撞的情况下很容易的进行运动,而不用处理刚体。角色控制器不受力的影响,仅仅当你调用Move函数时才运动。然后它将执行运动,但是受制于碰撞。

          Unity3D封装了一个非常好用的组件来实现第一人称视角与第三人称视角游戏开发,我们称他为角色控制器组件,几乎不用写一行代码就可以完成一切的操作---- Charactr Controller(角色控制器).

            1、调用的方法是simplemove()使物体移动;
                  首先为物体添加charactercontroller(角色控制器);

            2、角色控制器对象:private charactercontroller controller=null;
               
            3、角色移动的速度:private float movespeed=30.0f;

给游戏对象添加角色控制器过程:

               


举例:

  1. using UnityEngine;
  2. using System.Collections;

  3. public class Player2 : MonoBehaviour {
  4.         //如果用CharacterController(角色控制器),需要添加碰撞器
  5.         CharacterController controller;
  6.         public float speed=10;
  7.         void Start () {
  8.                 controller=this.GetComponent<CharacterController>();
  9.         }
  10.         void Update () {
  11.                 controller.SimpleMove (new Vector3(Input.GetAxis("Horizontal")*speed,0,Input.GetAxis("Vertical")*speed));
  12.         }
  13. }

射线

           射线,类比的理解就是游戏中的子弹。是在3D世界里中一个点向一个方向发射的一条无终点的线。在发射的过程中,一旦与其他对象发生碰撞,就停止发射。


           射线包括两个元素:ray.origin(射线起点);ray.direction(射线的方向

           创建一个射线的方法:ray(origin : vector3,direction : vector3) 

           定义一个光线投射碰撞:raycasthit hit;

           发射射线长度为:physics.raycast(ray,out hit,100);

           打印射线:debug.drawline(ray.origin,jit.point);


举例:


  1. using UnityEngine;
  2. using System.Collections;

  3. public class RayTest : MonoBehaviour {

  4.     // Use this for initialization
  5.     void Start () {
  6.     
  7.     }
  8.     
  9.     // Update is called once per frame
  10.     void Update () 
  11.     {
  12.         if(Input.GetMouseButton(0))
  13.         {
  14.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机发出到点击坐标的射线
  15.             RaycastHit hitInfo;
  16.             if(Physics.Raycast(ray,out hitInfo))
  17.             {
  18.                 Debug.DrawLine(ray.origin,hitInfo.point);//划出射线,只有在scene视图中才能看到
  19.                 GameObject gameObj = hitInfo.collider.gameObject;
  20.                 Debug.Log("click object name is " + gameObj.name);
  21.                 if(gameObj.tag == "boot")//当射线碰撞目标为boot类型的物品 ,执行拾取操作
  22.                 {
  23.                     Debug.Log("pick up!");
  24.                 }
  25.             }
  26.         }
  27.     }
  28. }

更多精彩请点击 http://www.gopedu.com/article


0 0