2D Shooting Question?

Hello guys,

It’s me again with a 2d problem that I can’t seem to solve. As I’ve noted in earlier posts the project I have been working on is a “tutorial” from the Brackeys “2D Platforming” series.

Now, I changed the shooting mechanic from the series to use a projectile system instead of using a drawline based one like Brackeys eventually used. Up to that point in the tutorial we were going to use a projectile solution and was changed because it was easier and that change didn’t sit well with me. So, I persisted with a projectile system and one particularly helpful user on the forums gave me code to do that :sunglasses:. It just had one teensy problem the bullet didn’t exactly go to where it was supposed to, probably because of the sprite I am using, the firing is a little off only by a few degrees, I could live with that, although at shallower angles the transform isn’t at the right angle and moving upwards instead of straight and at some particular angles the bullet prefab is bouncing off the platform :face_with_spiral_eyes:.

So, if anyone is willing to help me out with these problems please tell me which of the scripts would help? I have a weapons script, a movebullet script, as well as an BulletCollision script. Or, would putting all the source files in a Dropbox account be a better idea?

As always any and all help is greatly appreciated!

Regards,
CK.

Are you spawning the bullet with a rigid body? It could be reacting when it is created if it is being created in contact with the player rigid body. If you have an empty game object as the bullet spawn point you could try moving it away from the player body more to see if it helps. If it does then you could play with the positioning until it is ok &/or fix it using the physics layers.

Rightio, I’ll try that out and see what happens :).

EDIT: I tried moving around the firepoint position and it didn’t seem to make much of a difference at all. So I’m posting the code for the weapons script as that might help track down the error. I’m betting that it is the bulletDirection variable that is casing the problem - possibly. A word of warning thought there is a lot of commenting in the code. This is my first 2D project and I’m trying to keep everything straight in my head … emphasis on trying ;).

sing System.Collections;

//Basically a script/class to deal with:
//1. Raycasting - well not anymore thank goodness
//2. to detect a hit when the "fire1" button is hit or the left mouse button :)
//3. set bullet movement and call appropriate routine

public class Weapons_V : MonoBehaviour {

    //fireRate var to determine is the object/weapon is single burst or continiuos fire
    //using Unity Docs version this number should be quite small
    //works on seconds (also fraction of seconds)
    public float fireRate = 0;    //default value for single burst weapons

    //var for the damage weapon will do - deal with enemy health
    //TODO: make hitDamage to enemy actually work
    public float hitDamage = 10;        //default value - can be changed
    public LayerMask whatLayerToHit;

    private float timeToFire;            //a var to allow for bursts a a timed pace
    private Transform firePoint;        //var to the "FirePoint" game object

    //spawning FX section
    private float timeToSpawnFX = 0;    //lets see if this works
    private float FXspawnRate    = .1f;    //same here again use float get rid of brackeys division in the code


    //Var to store our BulletTrail Prefab
    //public Transform BulletTrailPrefab;
    public Transform MuzzleFlashPrefab;

    //turn BulletTrailPrefab into a rigidbody 2d object
    public Rigidbody2D projectile;
  
  
    //var to help control shooting rate - burst or single shot
    private float nextFire = 0;

  
    private Rigidbody2D clone1;    //component gotten in Awake() - will this work??


    //trying something new making the Vector2 vars
    //persist in memory by making them public/private
    //private 'should' work in this sense - should :)
    private Vector2 mousePos;
    private Vector2 firePointPosition;
    private Vector2 bulletDirection;

    public GameObject bulletThingy;
    GameObject go;

    //setup to get the laser_shot sound
    AudioSource audio;
    public AudioClip laserShot;


    /*void Start() {
        bulletThingy = GameObject.FindGameObjectWithTag ("RigidBullet");
    } */





    // Use this for initialization
    void Awake () {

        Rigidbody2D clone1 = GetComponent<Rigidbody2D> ();
        GameObject go = GetComponent<GameObject> ();

        firePoint = transform.FindChild ("FirePoint");

        //null checking routine
        if(firePoint==null){
            Debug.LogError("FirePoint fraked up!!!");
            }

        //get component for audio
        audio = GetComponent<AudioSource>();

    }//end Awake()
  

  
    // Update is called once per frame
    void Update () {
        //deal with weapons - single burst or multiple
        //outer if
        if (fireRate == 0) {
            //Shoot ();
            //inner if
            if(Input.GetButtonDown("Fire1")){
                Shoot();
                } //end inner if
            }//end outer if for the else command
        else{
            //inner if in the else function also using &&
            if (Input.GetButton("Fire1") && Time.time > nextFire) {

                //this below is unity docs example
                nextFire = Time.time + fireRate;
                //this is Brakeys code
                //timeToFire = Time.time + 1 / fireRate;
                Shoot ();
                //print ("Shit");
            }
        }

    }//end Update()



    void Shoot(){
        print("We are Shooting!");
        //store our mouse's X and Y co-ords in a Vector2 variable
        //for the raycasting
        //nb we are using World co-ords because the screen co-oords are very different and
        //  the makers of Unity decided to invert them for some strange reason
        //Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint (Input.mousePosition).x,
        //                               Camera.main.ScreenToWorldPoint (Input.mousePosition).y
        //                               );
        //maybe a much better way to get the mouse co-ords
        mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

  


        //set the position to a new var of the X and Y co-ords of firePoint transform
        //thus eliminatig the Z co-ord which we don't need
        //that is pretty cool
        Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);

        //now for the actual RayCast
        //RaycastHit2D hit = Physics2D.Raycast (firePointPosition, (mousePosition - firePointPosition),100, whatLayerToHit);
        //newer version
        RaycastHit2D hit = Physics2D.Raycast (firePointPosition, (mousePos - firePointPosition),100, whatLayerToHit);
      
        if (Time.time >= timeToSpawnFX) {
            ShotFX ();
            timeToSpawnFX =Time.time + FXspawnRate;
            }
        //ShotFX ();
        //put in function to spawn the BulletTrailPrefab
        //right here :P

        //show the Ray for testing purposes - Brackeys is using DrawLine for this - nil thios agam
        //make ray go ToString edges of screen by using * 100
        ////Debug.DrawLine (firePointPosition, (mousePosition - firePointPosition)*100, Color.cyan);
        //Debug.DrawRay (firePointPosition, (mousePosition - firePointPosition), Color.green);
        //newer version
        Debug.DrawRay (firePointPosition, (mousePos - firePointPosition), Color.green);


        //hit stuff this stuff is done away with
        if(hit.collider != null){
            Debug.DrawLine (firePointPosition, hit.point, Color.red);
            //when ray hits on object on selected layermask make line red
            //like the drawline code
            //Debug.DrawRay (firePointPosition, (mousePosition - firePointPosition), Color.red);
            //Debug.Log("We hit the: "+hit.collider.name+ "and did: "+hitDamage+ " damage!");

            }//end outer if
             
        }//end Shoot()



    //A 'void' function to create/instantiate the BulletTrailPrefab
    //and MuzzleFlashPrefab and make them visible
    //make
    void ShotFX(){

        //play the sound???
        audio.PlayOneShot(laserShot, 1.0f);

        //get bullet direction
        // from PGJ
        bulletDirection = (mousePos - firePointPosition).normalized;

        //GameObject go = Instantiate (bulletThingy, firePointPosition, Quaternion.identity) as GameObject;
        go = Instantiate (bulletThingy, firePoint.position, firePoint.rotation) as GameObject;


        //using Method Three as provided by: pgj
        //stored in document: Bullet Movement.odt
        //Directory:  This PC -> Documents
        go.GetComponent<MoveTrail_V> ().SetDirection (bulletDirection);


        Transform clon3 = Instantiate (MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
        clon3.parent = firePoint;

        //set up random size for the 'muzzle flash'
        float size = Random.Range (.6f, 1f);

        //don't need to worry about Z rotation
        clon3.localScale = new Vector3(size, size, size);
        Destroy (clon3.gameObject, .04f);

        }//end ShotFX



}//end class Weapons_V
1 Like

Does anyone have any ideas as to what else I might try?