首页 > 解决方案 > 无法在 Unity 中制作不平滑的移动脚本

问题描述

从昨天开始做一个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);
        }
    }
}

标签: c#unity3d

解决方案


您可以使用:

Input.GetAxisRaw("Horizontal");
Input.GetAxisRaw("Vertical");

这将使用更便携GetAxis的旧输入系统,而无需平滑GetAxis().

或者,如评论中所述,您可以替换Input.GetKeyDown()Input.GetKey()以检查是否持有密钥。


推荐阅读