Search Unity

Question How to Instantiate bullet from objects facing direction?

Discussion in 'Scripting' started by Cygnus_X1, Mar 20, 2023.

  1. Cygnus_X1

    Cygnus_X1

    Joined:
    Feb 17, 2023
    Posts:
    1
    I am trying to fire a bullet prefab from a player game object in the direction that the player is facing. I have been at this for two nights with no success. The bullet is a simple sphere with no rigidbody. I am trying to see if this can be done from the players script without the bullet having to have it's own script to move. Here is the code I have to move my player and Instantiate the bullet...
    Code (CSharp):
    1. public class MovePractice : MonoBehaviour
    2. {
    3.     // Start is called before the first frame update
    4.     private float rotAngle;
    5.     private float moveSpeed;
    6.     private Renderer render;
    7.     public GameObject spherePrefab;
    8.     void Start()
    9.     {
    10.        
    11.         render = GetComponent<Renderer>();
    12.         render.material.color = Color.grey;
    13.         rotAngle = 180;
    14.         moveSpeed = 5;
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.         MoveCube();
    21.         if (Input.GetKeyDown(KeyCode.Space))
    22.         {
    23.             var bullet = Instantiate(spherePrefab, transform.position, transform.rotation);
    24.            
    25.         }
    26.     }
    27.  
    28.     void MoveCube()
    29.     {
    30.         if (Input.GetKey("w"))
    31.         {
    32.             transform.position += transform.forward * moveSpeed * Time.deltaTime;
    33.         }
    34.         if (Input.GetKey("s"))
    35.         {
    36.             transform.Translate(new Vector3(0, 0, -moveSpeed * Time.deltaTime));
    37.         }
    38.         if (Input.GetKey("d"))
    39.         {
    40.             transform.Rotate(0, rotAngle * Time.deltaTime, 0);
    41.         }
    42.         if (Input.GetKey("a"))
    43.         {
    44.             transform.Rotate(0, -rotAngle * Time.deltaTime, 0);
    45.         }
    46.     }
    47. }
     
  2. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    494