C# 按键输入赢得';我们不能团结工作

C# 按键输入赢得';我们不能团结工作,c#,unity3d,C#,Unity3d,我一直在学习乒乓球教程,但我有一个问题 按箭头时球拍不动 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() {

我一直在学习乒乓球教程,但我有一个问题

按箭头时球拍不动

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));
        }
    }
}

我在inspector中为图像分配了一个键。

好的,那么您需要检查的是,项目设置中是否定义了键代码

最好使用以下代码来检测此类按键:

void Update () {
    if (Input.GetButton("Fire1") && Time.time > nextFire) {
        nextFire = Time.time + fireRate;
        Instantiate(projectile, transform.position, transform.rotation);
    }
}
资料来源: 此外,我还建议观看以下教程: 这一切都解释得很清楚

希望对你有帮助;)


编辑:将函数更改为void,因为您似乎正在使用C#

我想我明白了。您不需要在inspector中指定键代码。您可以直接从脚本访问它们。它应该简化您的脚本

与此相反:

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修饰符(| |)添加其他修饰符。另外,对于第二个播放机,请确保更改按键代码,否则两个拨杆将同时移动

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

在transfer.Translate()中,您希望在世界坐标(而非本地坐标)中随时间以恒定速度向上移动。这就是为什么要使用矢量2.up*速度*时间.deltaTime。Vector2.up与

new Vector2 (0f, 1f);
将其乘以速度以获得移动距离,然后乘以Time.deltaTime以获得此帧中移动距离。由于“更新”在每一帧中调用,因此将在每一帧中移动距离

向下移动时,Vector2.down与

new Vector2(0f, -1f);

希望这有帮助

我更新了它;)检查视频我相信它会有帮助。你试过在ifs内部调试吗?试着在那里打印一些东西,看看它是否符合条件。