Search Unity

Bullets and there Direction and rotation

Discussion in 'Community Learning & Teaching' started by Valnus, Jun 1, 2022.

  1. Valnus

    Valnus

    Joined:
    May 13, 2022
    Posts:
    6
    Hallo

    I am very new to Unity ( especial C# and the API ) and I am currently following on a Udemy course to learn some of the basics.

    I made a character that looks at your mouse pointer and can move and jump in 3D space not problem.

    The problem i have is that I create a gun and Bullet prefab and the scripting to fire the before mentioned. Except my results are very weird. Shooting on a axis that's not X the bullet will either stop and drift to a side and spin out of control. If you press back and fire in any direction it works as intended.

    I am very sure I have transform problem and I have tried to use transform.forward and transform.right to no effect.

    My code :

    Gun Logic :

    Code (CSharp):
    1. public class GunLogic : MonoBehaviour
    2. {
    3.     [SerializeField]
    4.     GameObject m_bulletPrefab;
    5.  
    6.     [SerializeField]
    7.     Transform m_bulletSpawnPoint;
    8.  
    9. // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.  
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         if (Input.GetButtonDown("Fire1"))
    19.         {
    20.             if (m_bulletPrefab && m_bulletSpawnPoint)
    21.             {
    22.                 Instantiate(m_bulletPrefab, m_bulletSpawnPoint.position, m_bulletSpawnPoint.rotation * m_bulletPrefab.transform.rotation);
    23.             }
    24.  
    25.         }
    26.     }
    27. }

    Bullet code :


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class BulletLogic : MonoBehaviour
    6. {
    7.     Rigidbody m_rigidbody;
    8.     float m_bulletSpeed = 10.0f;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         m_rigidbody = GetComponent<Rigidbody>();
    14.         if (m_rigidbody)
    15.         {
    16.  
    17.             m_rigidbody.velocity = transform.up * m_bulletSpeed;
    18.  
    19.         }
    20.     }
    21.  
    22.  
    23. }
    24.  
     

    Attached Files: