【发布时间】:2020-07-12 17:28:21
【问题描述】:
从昨天开始我开始做一个 2D 游戏,我在做角色移动的时候发现了一个问题。我想让角色向左、向右、向上和向下移动,因为我在使用新的 Unity 输入系统时遇到了困难,所以我使用了旧的 Input.GetAxis()。我的角色在移动,但我不喜欢平滑的移动,我希望玩家始终以相同的速度移动,并在我释放移动键的那一刻停止。但要知道,每次按键我只能让他动一点。
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AlternativeController : MonoBehaviour
{
public float speed;
bool canMove = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (canMove)
{
Move();
}
}
void Move()
{
if (Input.GetKeyDown("right"))
{
transform.Translate(speed, 0, 0);
}
if (Input.GetKeyDown("left"))
{
transform.Translate(-speed, 0, 0);
}
if (Input.GetKeyDown("up"))
{
transform.Translate(0, speed, 0);
}
if (Input.GetKeyDown("down"))
{
transform.Translate(0, -speed, 0);
}
}
}
【问题讨论】:
-
Input.GetKeyDown只被调用一次。您需要释放密钥才能再次调用该方法。您希望角色只要按下键就移动,因此将Input.GetKeyDown更改为Input.GetKey。只要你按住键就会被调用。