簡體   English   中英

按下空格鍵時子彈不會向前移動(Unity 2D)

[英]Bullet does not move forward when spacebar is pressed (Unity 2D)

我正在從以下站點復制項目: http : //blog.lessmilk.com/unity-spaceshooter-1/ http://blog.lessmilk.com/unity-spaceshooter-2/

但是,當按下空格鍵時,我的子彈不會向前移動。 以下是我的腳本:

宇宙飛船腳本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spaceshipScript : MonoBehaviour {

    public GameObject bullet;

    // Use this for initialization
    void Start () {

    }

    void Update() {
        // Get the rigidbody component
        //var r2d = GetComponent("Rigidbody2D");
        float speed = 10.0f;

        // Move the spaceship when an arrow key is pressed
        if (Input.GetKey (KeyCode.RightArrow))
            transform.position += Vector3.right * speed * Time.deltaTime;
        else if (Input.GetKey (KeyCode.LeftArrow))
            transform.position += Vector3.left * speed * Time.deltaTime;


        //BULLET
        //When spacebar is pressed
        if (Input.GetKeyDown(KeyCode.Space)) {
            Instantiate(bullet, transform.position, Quaternion.identity);
        }
    }
}

子彈腳本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class bulletScript : MonoBehaviour {

    public int speed = 8;

    // Use this for initialization
    void Start () {
        Input.GetKey (KeyCode.UpArrow);
        transform.position += Vector3.right * speed * Time.deltaTime;
    }

    void OnBecomeInvisible() {
        Destroy (gameObject);
    }

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

正如他們在評論中告訴您的那樣,您正在混合兩種不同的方法。 如果你想使用Time.deltaTime修改子彈的位置,你需要將該行移動到 Update()

但是,如果您想按照教程的方法,而不是從下到上射擊子彈,而是從左到右射擊,則只需更改軸即可(不要忘記為子彈添加剛體)

// Public variable 
public var speed : int = 6;

// Function called once when the bullet is created
function Start () {
    // Get the rigidbody component
    var r2d = GetComponent("Rigidbody2D");

    // Make the bullet move upward
    r2d.velocity.x = speed;
}

// Function called when the object goes out of the screen
function OnBecameInvisible() {
    // Destroy the bullet 
    Destroy(gameObject);
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM