【问题标题】:How to make 2D input controls in Unity?如何在 Unity 中制作 2D 输入控件?
【发布时间】:2013-12-23 14:28:18
【问题描述】:

很抱歉再次打扰您,但由于我是从 Unity 开始的,而且我对开发 2D 游戏非常感兴趣,并且像 2D Unity 示例项目没有设计 2D 控件一样,因此,我需要为它制作 2D 输入控件游戏,对于它,有人可以帮我为这个 2D 样本创建它们吗? 提前致谢。 最好的祝福 亚历杭德罗

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    作为一个非常简单的答案,您应该首先选择要为角色移动而保留的两个轴。例如,您可以选择沿xy 轴移动角色,而忽略z 轴。

    然后,您应该将水平和垂直轴输入映射到角色的移动,同时考虑移动速度(您可以将其定义为变量)以及最后一帧与实际帧之间经过的时间。

    因此,考虑在xy 轴上移动角色,您可以执行类似的操作:

    var speed = 20.0;
    
    function Update () {
       var x = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
       var y = Input.GetAxis("Vertical") * Time.deltaTime * speed;
       transform.Translate(x, y, 0);
    }
    

    这可以用自然语言翻译为:“在每一帧(因为你在 Update() 函数中),在 x 和 y 轴上翻译你的角色,关于最后两个之间经过的时间帧数和速度 (= 20)。"

    【讨论】:

    • 您好安德里亚,感谢您的帮助!我会试试的!
    【解决方案2】:

    我会建议与上一个答案类似的代码片段,只需进行一些小的调整,因为您还没有真正指定它是自上而下还是平台类型游戏,这是我在 c# 中建议的代码

    public float speed;                //Floating point variable to store the player's movement speed.
    
    private Rigidbody2D rb2d;        //Store a reference to the Rigidbody2D component required to use 2D Physics.
    
    // Use this for initialization
    void Start()
    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D> ();
    }
    
    //FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
    void FixedUpdate()
    {
        //Store the current horizontal input in the float moveHorizontal.
        float moveHorizontal = Input.GetAxis ("Horizontal");
    
        //Store the current vertical input in the float moveVertical.
        float moveVertical = Input.GetAxis ("Vertical");
    
        //Use the two store floats to create a new Vector2 variable movement.
        Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
    
        //Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
        rb2d.AddForce (movement * speed);
    }
    

    如果您的意思是更基于平台的动作,请告诉我,我也可以为您提供代码!需要注意的一件事是,我在定义速度之前使用了 public,因为它允许您调整统一 gui 中的值,这对于测试目的很有用。我在我以前的一个项目中发现了这段代码,它在那里工作得很好,所以它应该对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多