坦克移动控制代码优化,原先的有个奇怪的问题,按住W或者S的时候没法左右移动,因为 v != 0 被 return 掉了。
public float speed = 3;
private List<string> codelist = new List<string>();
private string lastKeyCode = string.Empty;
// Update is called once per frame
void Update()
{
SetLastKeyCode();
}
private void FixedUpdate()
{
PlayerMove();
}
private void PlayerMove()
{
Vector3 vector = new Vector3();
Quaternion quaternion = new Quaternion();
switch (lastKeyCode)
{
case "W":
vector = new Vector3(0, speed * Time.deltaTime, 0);
quaternion = Quaternion.Euler(0.0f, 0.0f, 0.0f);
break;
case "S":
vector = new Vector3(0, -speed * Time.deltaTime, 0);
quaternion = Quaternion.Euler(0.0f, 0.0f, 180.0f);
break;
case "A":
vector = new Vector3(-speed * Time.deltaTime, 0, 0);
quaternion = Quaternion.Euler(0.0f, 0.0f, 90.0f);
break;
case "D":
vector = new Vector3(speed * Time.deltaTime, 0, 0);
quaternion = Quaternion.Euler(0.0f, 0.0f, -90.0f);
break;
default:
vector = new Vector3(); break;
}
if (lastKeyCode != "")
{
//设置坦克的朝向
transform.rotation = quaternion;
//设置坦克的位置
transform.Translate(vector, Space.World);
}
}
#region SetLastKeyCode
private void SetLastKeyCode()
{
#region KeyDown
if (Input.GetKeyDown(KeyCode.W)) { MoveKeyDown("W"); }
if (Input.GetKeyDown(KeyCode.S)) { MoveKeyDown("S"); }
if (Input.GetKeyDown(KeyCode.A)) { MoveKeyDown("A"); }
if (Input.GetKeyDown(KeyCode.D)) { MoveKeyDown("D"); }
#endregion
#region KeyUp
if (Input.GetKeyUp(KeyCode.W)) { MoveKeyUp("W"); }
if (Input.GetKeyUp(KeyCode.S)) { MoveKeyUp("S"); }
if (Input.GetKeyUp(KeyCode.A)) { MoveKeyUp("A"); }
if (Input.GetKeyUp(KeyCode.D)) { MoveKeyUp("D"); }
#endregion
}
private void MoveKeyDown(string keyCode)
{
if (!codelist.Contains(keyCode))
{
codelist.Add(keyCode);
}
if (codelist.Count > 0)
{
var key = codelist[codelist.Count - 1];
lastKeyCode = key;
}
}
private void MoveKeyUp(string keyCode)
{
codelist.RemoveAll(key => key.Contains(keyCode));
if (codelist.Count > 0)
{
var key = codelist[codelist.Count - 1];
lastKeyCode = key;
}
else
{
lastKeyCode = string.Empty;
}
}
#endregion