2D Shooting Problem?

Hello guys,

In my current project I am trying to implement a projectile shooting system that goes directly to the mouse position, however, because of reasons unknown to me, be it a problem in the code or, a problem in my sprite design - I cannot get it to go to the cursor. Which may or may not be causing other problems in the gameplay like the bullet seeming to bounce of the platform and also the bullet travelling along the platform and falling off instead of exploding like it’s supposed to :(.

I have included the weapons script and the movebullet script. I would also be willing to put all the source files in a Dropbox account to get a resolution to the problem.

As always any and all help is greatly appreciated!

Regards,
CK.

using 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??

    //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

Script to move the projectile:

using UnityEngine;
using System.Collections;

public class MoveTrail_V : MonoBehaviour {

    public int moveSpeed=100;
    public int speed = 200;
    private Rigidbody2D rb;
    public Vector2 velocity;

    public float bullSpeed = 10;

    //create a Vector2 var: dir - for SetDirection to use
    //only needs to be private - initally zeroed out
    private Vector2 dir = Vector2.zero;

    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody2D> ();
    }
 
    // Update is called once per frame
    //move the prefab across the screen
    /*void FixedUpdate () {

        rb.MovePosition ( (Vector2)transform.position + dir * bullSpeed * Time.fixedDeltaTime);
        Destroy (this.gameObject, 5);

    }*/

    void Update (){
        rb.MovePosition( (Vector2) transform.position + dir * bullSpeed* Time.deltaTime);
    }

    //takes a Vector2 vardirection
    public void SetDirection(Vector2 direction){

        this.dir = direction;
 
    }//end SetDirection()

}// End class MoveTrail_V

i didnot used moveposition :frowning:
making space shooter now, and i dont have moving script for bullets, just instaniate them with force.impuls

if (canFire)
        {
            canFire = false;
            if (target != null)
            {
                Vector3 dir = (target.transform.position - transform.position);
                dir = Vector3.Normalize(dir) * bSpeed;
                Rigidbody2D rb;
                GameObject bl;
                bl = (GameObject)Instantiate(bullet, firePoint.transform.position, transform.rotation);
                rb = bl.GetComponent<Rigidbody2D>();
                rb.AddForce(dir, ForceMode2D.Impulse);
            }
        }

Thanks so much for the reply :sunglasses:.

As soon as I have some free time from Martial Arts - maybe next week some time :face_with_spiral_eyes: - I’ll modify my project and plug that code into it and see what happens. It would be good to fix this error that I’ve had for quite some time.

Cheers,
CK.