unity用方向键来控制角色上楼梯

来源:互联网 发布:汽车工作知乎 编辑:程序博客网 时间:2024/06/05 20:31

自动寻路可以实现角色自动到任意的地方,也可以上楼,可我希望通过方向键来实现角色的移动和上楼梯。可是不同的楼梯有不同的台阶高度,若给他设定一个固定的值。那么使用起来不方便,而且在判断上楼还是下楼时比较难,如何让角色在y轴上的移动随着下一步的高度来改变呢?

若是在复杂的地形中,或许我们可以用Terrain.activeTerrain.SampleHeight(transform.position);这个函数。

public class example : MonoBehaviour {
void LateUpdate() {transform.position.y = Terrain.activeTerrain.SampleHeight(transform.position);}}

然而楼梯等就不是地形里的了,要获取其他的物体的为位置,我们可以使用射线Ray。

origin  起点;

direction 方向;

GetPoint(float distance) 获取点返回沿着射线在distance距离单位的点

还有RaycastHit 光线碰撞器。用来获取碰撞后的信息反馈。

一般使用的是这个函数static function Raycast (origin : Vector3direction : Vector3distance : float = Mathf.InfinitylayerMask : int = kDefaultRaycastLayers) : bool

若以碰撞提产生量交叉碰撞,返回true,或则返回false。

我们在使用时可以Physics.Raycast(Ray ray ,out  hit);       用一个out变量来将它们都带回。

好了,接下来就是写移动的代码了,,我用的是第一人称角色,所以前进键来判断,,目前尚未添加后退键的判断代码,总之,那也是同理得的啦。

using System.Collections;using System.Collections.Generic;using UnityEngine;public class controlmove : MonoBehaviour {public float speed;public Vector3 RayOrigin;Ray ray;// Use this for initializationvoid Start () {speed = 1.0f;}// Update is called once per framevoid Update () {        RayOrigin = new Vector3 (this.transform.position.x, this.transform.position.y , this.transform.position.z )+this.transform.up*2+this.transform.forward*speed;ray.origin = RayOrigin;ray.direction = new Vector3 (0, -1, 0);RaycastHit hit;if (Physics.Raycast (ray, out hit)) {Debug.DrawLine (ray.origin, hit.point, Color.red);}if (Input.GetKey (KeyCode.UpArrow)) {Debug.Log (hit.point);this.transform.Translate (0, -this.transform.position.y + hit.point.y, Time.deltaTime * speed);}if (Input.GetKey (KeyCode.DownArrow))this.transform.Translate (0, 0, -Time.deltaTime);if (Input.GetKey (KeyCode.LeftArrow))this.transform.Rotate (0, -1, 0);if(Input.GetKey(KeyCode.RightArrow))this.transform.Rotate(0,1,0);}}
因为把ray用红色画出来了,因此我们可以清晰的看到有红线,并在碰撞到楼梯时射线结束。

这里要注意的问题是楼梯等要加上碰撞体,同时还要注意碰撞体的类型!!!

还有就是在确定rayorigin的时候,我们要让射线在我角色的正前方,不是简单的

RayOrigin = new Vector3 (this.transform.position.x, this.transform.position.y+2, this.transform.position.z +1);

不然得到的是一个世界坐标下的方向移动,在角色的转向过程中,不一定会在角色的正前方。应该用下面这个函数

RayOrigin = new Vector3 (this.transform.position.x, this.transform.position.y , this.transform.position.z )+this.transform.up*2+this.transform.forward*speed;

这样就完成了。


原创粉丝点击