且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按键输入在Unity中不起作用

更新时间:2023-11-17 22:16:22

我想我明白了.您不需要在检查器中分配键码.您可以直接从脚本访问它们.它应该简化您的脚本.

I think I get you. You dont need to assign the Keycodes in the inspector. You can access them directly from the script. It should simplify your script.

代替此:

using UnityEngine;
using System.Collections;

public class MoveRacket : MonoBehaviour
{
    // up and down keys (to be set in the Inspector)
    public KeyCode up;
    public KeyCode down;

    void FixedUpdate()
    {
        // up key pressed?
        if (Input.GetKey(up))
        {
            transform.Translate(new Vector2(0.0f, 0.1f));
        }

        // down key pressed?
        if (Input.GetKey(down))
        {
            transform.Translate(new Vector2(0.0f, -0.1f));
        }
    }
}

尝试一下:

using UnityEngine;
using System.Collections;

public class MoveRacket : MonoBehaviour
{
        public float speed = 30f;
         //the speed at which you move at. Value can be changed if you want 

    void Update()
    {
        // up key pressed?
        if (Input.GetKeyDown(KeyCode.W)
        {
            transform.Translate(Vector2.up * speed * time.deltaTime, Space.world);
        }

        // down key pressed?
        if (Input.GetKeyDown(KeyCode.S))
        {
            transform.Translate(Vector2.down * speed * time.deltaTime, Space.World);
        }
    }
}

假设您要使用wasd键进行移动.如果需要,可以使用OR修饰符(||)添加其他项.另外,对于第二位玩家,请确保更改键码,否则两个拨片将同时移动.

Assuming you want to use wasd keys for movement. You can add additional ones using an OR modifier (||) if you want. Also, for the second player, be sure to change the keycodes, or both paddles will move at the same time.

代码说明: 速度变量是您要移动的速度.根据需要进行更改.

CODE EXPLANATION: the speed variable is what speed you want to move at. Change it as per your needs.

在transfor.Translate()中,您希望随着时间的推移以恒定的速度在世界坐标(而不是局部坐标)中向上移动.这就是为什么要使用Vector2.up * speed * time.deltaTime的原因. Vector2.up与

in transfor.Translate(), you want to move up, at a constant speed, over time, in world coordinates (not local). That is why you use Vector2.up * speed * time.deltaTime. Vector2.up is the same as

new Vector2 (0f, 1f);

您将其乘以速度以获取要移动的距离,然后乘以Time.deltaTime以获取在该帧中要移动的距离.由于每帧都会调用更新,因此您将移动每一帧的距离.

you multiply it by speed to get the distance to move, and then by Time.deltaTime to get the distance to move in this frame. Since Update is called every frame, you will move the distance every frame.

向下移动时,Vector2.down与

In moving down, Vector2.down is the same as

new Vector2(0f, -1f);

希望这对您有帮助!