脚本问题统一3D

时间:2016-03-03 07:42:42

标签: unity3d unityscript

这是我的立方体游戏代码。其实我希望这段代码运行如下: 当我按下“空间”时,它必须生成一个立方体,当前它生成多个立方体一次按下“空格”按钮。 其次,当我使用箭头键时,它必须从我当前站立的位置生成立方体,但暂时它只是从中心生成立方体。

using UnityEngine;
using System.Collections;

public class fire : MonoBehaviour {

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name == "brick" || collision.gameObject.name == "a" || collision.gameObject.name == "b")
        {
            Destroy(collision.gameObject);
        }
    }

    public float speed;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, 0f);

        if (Input.GetKey(KeyCode.Space))
        {
            transform.Translate(speed * Vector3.up * Time.deltaTime);            
        }
        Vector3 temp = transform.position;
        if (Input.GetKey(KeyCode.Space))
        {

            GameObject textObject = (GameObject)Instantiate(Resources.Load("ball"));
        }

    }

}

4 个答案:

答案 0 :(得分:2)

  1. 尝试使用Bash Redirections或GetKeyDown而不是GetKey。

  2. 您可以使用要实例化对象的位置调用Input.GetKeyUp

答案 1 :(得分:1)

如何使用Input.GetKeyUp ???

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Update() {
        if (Input.GetKeyUp("space"))
            print("space key was released");

    }
}

答案 2 :(得分:0)

From http://docs.unity3d.com/ScriptReference/Input.GetKey.html“当用户按下由名称标识的密钥时返回true。想想自动启动。”因此,如果您按下键1/10秒并且每秒调用60次更新,您将获得大约六个立方体。

通常,您希望将对象创建绑定到keydown或keyup事件,因为它只会触发一次。

答案 3 :(得分:0)

您可能想使用Input.GetKeyDown(“ space”)实例化gameObject一次。这是因为它只会在您按下框架的期间返回 而您仍然按下按钮时,您正在使用的Input.GetKey将返回true。 因此,您可以执行以下操作:

void Update()
{
   if(Input.GetKeyDown("space")
   {
      GameObject textObject = (GameObject)Instantiate(Resources.Load("ball"));
   }
}
相关问题