鼠标控制移动
using UnityEngine;
using System.Collections;
public class MyMouseMoveControll : MonoBehaviour {
// 角色状态
public const int PLAY_IDE = 0;
public const int PLAY_WALK = 1;
public const int PLAY_RUN = 2;
// 角色当前状态
private int currState = 0;
// 世界坐标
private Vector3 pointIn3D;
// 点击间隔时差
private float time = 0f;
// 这里暂时使用主摄像机, 应该作为参数, 外界传入摄像机实例
//public GameObject camera;
public CharacterController controll;
void Start ()
{
controll = GetComponent< CharacterController > ();
SetCurrState (PLAY_IDE);
}
void Update ()
{
MouseMove ();
}
void MouseMove()
{
if (Input.GetMouseButtonDown (0))
{
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
RaycastHit hit;
if( Physics.Raycast( ray, out hit ) )
{
if( hit.collider.tag == "Plane" )
{
pointIn3D = hit.point;
// 角色朝向
transform.LookAt( new Vector3( pointIn3D.x, transform.position.y, pointIn3D.z ) );
TimeRealtimeSinceStartup();
}
}
FixedUpdate();
}
}
void FixedUpdate()
{
switch (currState)
{
case PLAY_IDE:
break;
case PLAY_WALK:
Move ( 0.05f );
break;
case PLAY_RUN:
Move ( 0.1f );
break;
}
}
void Move( float speed )
{
if ( 0.3f <= Mathf.Abs (Vector3.Distance (pointIn3D, transform.position)))
{
Vector3 v = Vector3.ClampMagnitude (pointIn3D - transform.position, speed);
controll.Move ( v );
}
else
{
SetCurrState( PLAY_IDE );
}
}
void TimeRealtimeSinceStartup()
{
if (0.2f >= (Time.realtimeSinceStartup - time))
{
SetCurrState (PLAY_RUN);
}
else
{
SetCurrState( PLAY_WALK );
}
time = Time.realtimeSinceStartup;
}
void SetCurrState( int state )
{
switch (state)
{
case PLAY_IDE:
pointIn3D = transform.position;
// play ide animation
break;
case PLAY_WALK:
// play walk animation
break;
case PLAY_RUN:
// play run animation
break;
}
currState = state;
}
}