思路
1.坐标平移
(1)使用input.Get获取按键: 检测按键是否持续按下
(2)加上偏移量
以下是对x坐标移动的控制
void Update()
{
if (Input.GetKey(KeyCode.A))
{
MoveControl_X(-WalkSpeed);
}
else if (Input.GetKey(KeyCode.D))
{
MoveControl_X(WalkSpeed);
}
}
private void MoveControl_X(float WalkSpeed)
{
Vector2 dir = transform.position;
dir.x += WalkSpeed;
transform.position = dir;
}
2.对刚体物件改变速度
(1)使用Rigidbody组件
(2)input.Get判断按下时,赋予一个速度
(3)inPut。Getup判断松开时,速度改为0
void Update()
{
if(Input.GetKey(KeyCode.A))
{
Vector2 dir = new Vector2(-1, 0);
rgd.velocity = (dir * force);
}
else if(Input.GetKey(KeyCode.D))
{
Vector2 dir = new Vector2(1, 0);
rgd.velocity = (dir * force);
}
if (Input.GetKeyUp(KeyCode.A))
{
rgd.velocity = new Vector2(0, 0);
}
if (Input.GetKeyUp(KeyCode.D))
{
rgd.velocity = new Vector2(0, 0);
}
}
如果有更好的思路,欢迎讨论