Search Unity

Shooting a bullet in 2D Game

Discussion in '2D' started by Hyobin_Kim, Jul 13, 2018.

  1. Hyobin_Kim

    Hyobin_Kim

    Joined:
    Feb 25, 2018
    Posts:
    17
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerControl : MonoBehaviour
    6. {
    7.     //Player's Bullet Prefab, BulletPositions
    8.     public GameObject playerBulletGo;
    9.     public GameObject bulletPosition01;
    10.     public GameObject bulletPosition02;
    11.  
    12.  
    13.     //what I tried
    14.     //public Transform bulletPosition01;
    15.     //public Transform bulletPosition02;
    16.  
    17.     //for the speed of Player
    18.     public float speed;
    19.  
    20.  
    21.     // Use this for initialization
    22.     void Start ()
    23.     {
    24.        
    25.     }
    26.    
    27.     // Update is called once per frame
    28.     void Update ()
    29.     {
    30.         if (Input.GetKeyDown (KeyCode.Space))
    31.         {
    32.             //instantiate bullets from position01
    33.             GameObject bullet01 = (GameObject)Instantiate (playerBulletGo);
    34.             //seeting the bullet's initial posiiton
    35.             bullet01.transform.position = bulletPosition01.transform.position;
    36.  
    37.             //instantiate bullets from position02
    38.             GameObject bullet02 = (GameObject)Instantiate (playerBulletGo);
    39.             //seeting the bullet's initial posiiton
    40.             bullet02.transform.position = bulletPosition02.transform.position;
    41.  
    42.             //what I tried
    43. //            Instantiate (playerBulletGo, bulletPosition01);
    44. //            Instantiate (playerBulletGo, bulletPosition02);
    45.  
    46.         }
    this is my code for making SpaceShooter 2D

    here for shooting bullets, in the video i am watching,

    first, instantiate the bullet's prefab and set the bullet's initial position by using transform.position property of shootingpositon game object

    but I tried another way, creating a public GameObject variable for bulltPosition

    and simply put "instantiate()" with second argument

    but the result was weird

    butllet was instantiate not from "bulletPosiiton"

    I want to know the rason

    Thank you
     

    Attached Files:

  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Check out the documentation for Instantiate

    You need to pass in a Vector3 for the position, and a Quaternion for rotation. So it would be bulletPosition01.transform.position, not just the game object itself.

    Instantiate(playerBulletGo, bulletPosition01.transform.position, Quaternion.identity)