Mariam Syafiqah Saidi
Mariam Syafiqah Saidi

Reputation: 35

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

I'm replicating project from this site below: http://blog.lessmilk.com/unity-spaceshooter-1/ http://blog.lessmilk.com/unity-spaceshooter-2/

But, my bullet does not move forward when the spacebar is pressed. Below are my scripts:

spaceshipScript:

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

bulletScript:

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 () {
        
    }
}

Upvotes: 0

Views: 786

Answers (1)

Ignacio Alorre
Ignacio Alorre

Reputation: 7605

As they are telling you in the comments, you are mixing two different approaches. If you want to modify the position of the bullet using Time.deltaTime you need to move that line to Update()

However if you want to follow the approach of the tutorial, but instead of shooting the bullet from bottom to top, you want to shoot from left to right, you should just change the axis (And dont forget to add a rigid body to the bullet)

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

Upvotes: 1

Related Questions