unity——使用角色控制器组件+射线移动

首先要导入unity标准资源包Character Controllers 这个标准资源包,为了方便,还添加了两外一个资源包Scripts,后者包含了一些基本的脚本个摄像机脚本。

没错,这次我们要使用其中一个摄像机脚本, 创建一个terrain (地形ller组件(如),创建一个capsule ,并为这个胶囊提添加 CharactContro果没有导入角色标准资源包的话竟不能被添加该组件),注意只是一个CharactController 组件而已。

当我们点击 add Component——Character的时候会有以下三个选项,第一个是第一人称视角,后面两个是第三人称视角。有什么区别,还没有去研究:

 

比如我们添加了第一个“CharacterMotor” ,添加以后系统自动为我们添加了包含 CharactorController 组件在内的两个组件。这里我们只需要CharacterController 这个组件,要把另外一个删除掉。如果添加了后面两个“FPS Input Controller” 或者 “Platform Input Controller”同样也是要删除多余的只剩下 CharacterController  这个组件。因为我们只是用到了 

CharacterController.Move这个函数

function Move (motion : Vector3) : CollisionFlags

对这个函数的描述我也没看太懂,大概是按照参数的方向移动了参数的长度、、、、、、吧0.0

这个组件只是为控制他移动提供了基础。要想实现移动还要我们添加一个移动的脚本,于是这个叫做 MyController 的脚本诞生了。

上代码:

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class MyController : MonoBehaviour {
 5     private Vector3 mousePoint;
 6     public float speed=0.1f;
 7     // Use this for initialization
 8     void Start () {
 9     
10     }
11     
12     // Update is called once per frame
13     void Update () {
14     if (Input.GetMouseButtonDown(0)) {
15             Ray myRay=Camera.main.ScreenPointToRay(Input.mousePosition);
16             RaycastHit hit;
17 
18             if (Physics.Raycast(myRay,out hit)) {
19                 mousePoint=hit.point;
20                 transform.LookAt(new Vector3(mousePoint.x,transform.position.y,mousePoint.z) );
21             }
22 
23             print(Vector3.Distance(mousePoint,transform.position));
24         }
25         Move(speed);
26     }
27 
28     void Move(float speed)
29     {
30         if (Mathf.Abs(Vector3.Distance(transform.position,mousePoint))>=1f) {
31 
32             CharacterController controller = GetComponent<CharacterController>();
33             Vector3 v=Vector3.ClampMagnitude(mousePoint-transform.position,speed);
34             controller.Move(v);
35         }
36         else
37         {
38             Debug.Log("已到达终点");
39         }
40 
41     }
42 }

 第 30行 Vector3.Distance 这个函数的解释:

static function Distance (a : Vector3, b : Vector3) : float

这个函数返回 a、b 两点之间的距离,这个距离永远是正值!!

官方的解释,这个函数等同于(a-b).magnitude而(a-b).magnitude是怎么计算的呢?看下面:

Vector3.magnitude

返回向量的长度(只读)。向量的长度是(x*x+y*y+z*z)的平方根。

由此可知。返回永远都不可能是负值。

所以,代码中第30行的 Mathf.Abs  取绝对值的函数是没有必要的

另外第33行也有一个函数:

Vector3.ClampMagnitude

这个函数的描述:

static function ClampMagnitude (vector : Vector3, maxLength : float) : Vector3

返回向量的长度,最大不超过maxLength所指示的长度。

也就是说,钳制向量长度到一个特定的长度。

呦描述可知,该方法返回了一个vector3类型的值,这个向量可以看做是第一个参数的副本,但是有一点:它的长度被第二个参数限制了。

下面来看看run 的结果:

 

无法上传运行图片。。。晕

转载于:https://www.cnblogs.com/devilWang/p/4674054.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值