自己在学习unity的课程中遇到了,有的地方还没怎么太理解上去,先做个笔记,顺便看看有没有需要的人。
1.搭建一个小场景,一个需要控制的“人”(添加CharacterController组件),地面和几个遮挡物(添加Collider),比如我搭的小场景:
2.先写一个能获取到我们按下鼠标左键,它的位置座标一定就要发生变化,我们需要获取到移动后的位置对于初始位置做出的位移。
using UnityEngine;
using System.Collections;
public class walk : MonoBehaviour {
GameObject obj;
Vector3 startpos;//定义初始位置
public static Vector3 camDelta;//定义移动后的位置对于初始位置做出的位移
void Start () {
}
void Update () {
//如果我们按下鼠标左键 0表是左键 1表示右键 2表示中间
if(Input.GetMouseButton(0)){
if (startpos == Vector3.left) //第一次按鼠标左键
{
startpos = Input.mousePosition;//鼠标的位置就是初始的位置
}else {
camDelta = Input.mousePosition - startpos;//获取△t
}
}
else if (Input.GetMouseButtonUp(0))//如果松开了左键
{
startpos = Vector3.left;//初始化
camDelta = Vector3.zero;//初始化
}
// Debug.Log(camDelta);
}
}
3.在写一个可以让人发生位置移动的脚本
using UnityEngine;
using System.Collections;
public class actor :walk {
CharacterController cc;
int speed = 1;
// Use this for initialization
void Start () {
cc = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update () {
if(walk.camDelta==Vector3.left){
return;
}
Vector3 WorldYDirection = Camera.main.transform.TransformDirection(Vector3.up);
Vector3 GroundYDirection = new Vector3(WorldYDirection.x,0,WorldYDirection.z).normalized*walk.camDelta.y;
Vector3 WorldXDirection = Camera.main.transform.TransformDirection(Vector3.right);
Vector3 GroundXDirection = new Vector3(WorldXDirection.x, 0, WorldXDirection.z).normalized * walk.camDelta.x;
Vector3 direction = (GroundXDirection + GroundYDirection).normalized;
Vector3 motion = direction * speed;
motion.y = -1000;//紧贴地面
Debug.Log(motion);
cc.Move(motion);
}
}
还有一些不懂的地方,要是有错的地方麻烦告诉我一声,要是有有时间的人明白后面部分代码的人也麻烦联系一下我,感激不尽!
4.运行之后,“人”就可以根据鼠标进行运动,遇到遮挡就会停下过不去。截几个图看下最后结果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)