简单的角色响应鼠标而移动

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 ;
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值