按键控制移动
using UnityEngine;
using System.Collections;
public class MyMoveControll : MonoBehaviour {
// 自定义方向系数
public const int PLAY_UP = 0;
public const int PLAY_RIGHT = 1;
public const int PLAY_DOWN = 2;
public const int PLAY_LEFT = 3;
// 人物速度 ( 为了方便测试, 可更改为 public 属性, 在面板中设置数值 )
private int moveSpeed = 10;
// 人物当前方向状态
private int currState = 0;
void Awake()
{
currState = PLAY_UP;
}
void Update ()
{
KeyControll ();
// Draw Line
Quaternion qua = transform.rotation;
Vector3 f = transform.position + (qua * Vector3.forward) * 5;
Debug.DrawLine (transform.position, f, Color.red);
}
// 按钮控制
void KeyControll()
{
float xMovement = Input.GetAxis("Horizontal");
float zMovement = Input.GetAxis("Vertical");
float tempAngle = Mathf.Atan2( zMovement, xMovement );
xMovement *= Mathf.Abs( Mathf.Cos ( tempAngle ) );
zMovement *= Mathf.Abs( Mathf.Sin ( tempAngle ) );
Vector3 moveDirection = new Vector3( xMovement, 0, zMovement );
moveDirection = transform.TransformDirection( moveDirection );
// 防止前移
moveDirection.y = 0;
if (Input.GetKey (KeyCode.A))
{
GetComponent< CharacterController > ().Move( -1 * moveDirection * Time.deltaTime );
}
else if (Input.GetKey (KeyCode.D))
{
GetComponent< CharacterController > ().Move( moveDirection * Time.deltaTime );
}
else if (Input.GetKey (KeyCode.S))
{
GetComponent< CharacterController > ().Move( -1 * moveDirection * Time.deltaTime );
}
else if (Input.GetKey (KeyCode.W))
{
GetComponent< CharacterController > ().Move( moveDirection * Time.deltaTime );
}
}
}
按键获取方式【 2 】
float KeyVertical = Input.GetAxis("Vertical");
float KeyHorizontal = Input.GetAxis("Horizontal");
if(KeyVertical == -1)
{
setGameState(PLAY_LEFT);
}
else if(KeyVertical == 1)
{
setGameState(PLAY_RIGHT);
}
if(KeyHorizontal == 1)
{
setGameState(PLAY_DOWN);
}
else if(KeyHorizontal == 1)
{
setGameState(PLAY_UP);
}