actor类
//处理移动距离,核心是找到角色坐标在世界坐标的向量的投影(x,y,z),然后在世界坐标中合成,此CC是在地面行走,所以Y轴投影始终置为0;
using UnityEngine;
using System.Collections;
public class actor : MonoBehaviour {
public float speed=0.1f;
CharacterController cc;
// Use this for initialization
void Start () {
cc = GetComponent<CharacterController> ();
}
// Update is called once per frame
void Update () {
if (stick.camDelta == Vector3.left)
{
return ;
}
//获取CC摄像机Y轴在世界坐标系中的投影
Vector3 WorldYDirection = Camera .main .transform .TransformDirection (Vector3.up);
//将上段代码取得的投影归一化(normalize),也就是变成单位向量
Vector3 GroundYDirection = new Vector3 (WorldYDirection .x, 0, WorldYDirection .z).normalized * stick.camDelta .y;
Vector3 WorldXDirection = Camera.main.transform .TransformDirection (Vector3.right);
Vector3 GroundXDirection = new Vector3 (WorldXDirection.x, 0, WorldXDirection.z).normalized * stick.camDelta .x;
Vector3 direction = (GroundXDirection + GroundYDirection).normalized;
Vector3 motion = direction * speed;
.//始终让CC紧贴地面
motion .y = -1000;
cc.Move (motion);
}
}
stick类
//响应鼠标的点击和移动
public class stick : MonoBehaviour {
public static Vector3 camDelta;
private Vector3 startpos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0)) {
if (startpos == Vector3.left) {
startpos = Input.mousePosition;
} else {
camDelta = Input .mousePosition - startpos;
}
}
else if (Input.GetMouseButtonUp (0))
{
camDelta=Vector3.zero ;
startpos=Vector3.left ;
}
}
}