Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

2D Shooting Question?

Discussion in '2D' started by CelticKnight, Aug 30, 2015.

  1. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    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 :cool:. 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 :confused:.

    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.
     
  2. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570
    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.
     
  3. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    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 ;).

    Code (CSharp):
    1. sing System.Collections;
    2.  
    3. //Basically a script/class to deal with:
    4. //1. Raycasting - well not anymore thank goodness
    5. //2. to detect a hit when the "fire1" button is hit or the left mouse button :)
    6. //3. set bullet movement and call appropriate routine
    7.  
    8. public class Weapons_V : MonoBehaviour {
    9.  
    10.     //fireRate var to determine is the object/weapon is single burst or continiuos fire
    11.     //using Unity Docs version this number should be quite small
    12.     //works on seconds (also fraction of seconds)
    13.     public float fireRate = 0;    //default value for single burst weapons
    14.  
    15.     //var for the damage weapon will do - deal with enemy health
    16.     //TODO: make hitDamage to enemy actually work
    17.     public float hitDamage = 10;        //default value - can be changed
    18.     public LayerMask whatLayerToHit;
    19.  
    20.     private float timeToFire;            //a var to allow for bursts a a timed pace
    21.     private Transform firePoint;        //var to the "FirePoint" game object
    22.  
    23.     //spawning FX section
    24.     private float timeToSpawnFX = 0;    //lets see if this works
    25.     private float FXspawnRate    = .1f;    //same here again use float get rid of brackeys division in the code
    26.  
    27.  
    28.     //Var to store our BulletTrail Prefab
    29.     //public Transform BulletTrailPrefab;
    30.     public Transform MuzzleFlashPrefab;
    31.  
    32.     //turn BulletTrailPrefab into a rigidbody 2d object
    33.     public Rigidbody2D projectile;
    34.  
    35.  
    36.     //var to help control shooting rate - burst or single shot
    37.     private float nextFire = 0;
    38.  
    39.  
    40.     private Rigidbody2D clone1;    //component gotten in Awake() - will this work??
    41.  
    42.  
    43.     //trying something new making the Vector2 vars
    44.     //persist in memory by making them public/private
    45.     //private 'should' work in this sense - should :)
    46.     private Vector2 mousePos;
    47.     private Vector2 firePointPosition;
    48.     private Vector2 bulletDirection;
    49.  
    50.     public GameObject bulletThingy;
    51.     GameObject go;
    52.  
    53.     //setup to get the laser_shot sound
    54.     AudioSource audio;
    55.     public AudioClip laserShot;
    56.  
    57.  
    58.     /*void Start() {
    59.         bulletThingy = GameObject.FindGameObjectWithTag ("RigidBullet");
    60.     } */
    61.  
    62.  
    63.  
    64.  
    65.  
    66.     // Use this for initialization
    67.     void Awake () {
    68.  
    69.         Rigidbody2D clone1 = GetComponent<Rigidbody2D> ();
    70.         GameObject go = GetComponent<GameObject> ();
    71.  
    72.         firePoint = transform.FindChild ("FirePoint");
    73.  
    74.         //null checking routine
    75.         if(firePoint==null){
    76.             Debug.LogError("FirePoint fraked up!!!");
    77.             }
    78.  
    79.         //get component for audio
    80.         audio = GetComponent<AudioSource>();
    81.  
    82.     }//end Awake()
    83.  
    84.  
    85.  
    86.     // Update is called once per frame
    87.     void Update () {
    88.         //deal with weapons - single burst or multiple
    89.         //outer if
    90.         if (fireRate == 0) {
    91.             //Shoot ();
    92.             //inner if
    93.             if(Input.GetButtonDown("Fire1")){
    94.                 Shoot();
    95.                 } //end inner if
    96.             }//end outer if for the else command
    97.         else{
    98.             //inner if in the else function also using &&
    99.             if (Input.GetButton("Fire1") && Time.time > nextFire) {
    100.  
    101.                 //this below is unity docs example
    102.                 nextFire = Time.time + fireRate;
    103.                 //this is Brakeys code
    104.                 //timeToFire = Time.time + 1 / fireRate;
    105.                 Shoot ();
    106.                 //print ("S***");
    107.             }
    108.         }
    109.  
    110.     }//end Update()
    111.  
    112.  
    113.  
    114.     void Shoot(){
    115.         print("We are Shooting!");
    116.         //store our mouse's X and Y co-ords in a Vector2 variable
    117.         //for the raycasting
    118.         //nb we are using World co-ords because the screen co-oords are very different and
    119.         //  the makers of Unity decided to invert them for some strange reason
    120.         //Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint (Input.mousePosition).x,
    121.         //                               Camera.main.ScreenToWorldPoint (Input.mousePosition).y
    122.         //                               );
    123.         //maybe a much better way to get the mouse co-ords
    124.         mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    125.  
    126.  
    127.  
    128.  
    129.         //set the position to a new var of the X and Y co-ords of firePoint transform
    130.         //thus eliminatig the Z co-ord which we don't need
    131.         //that is pretty cool
    132.         Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
    133.  
    134.         //now for the actual RayCast
    135.         //RaycastHit2D hit = Physics2D.Raycast (firePointPosition, (mousePosition - firePointPosition),100, whatLayerToHit);
    136.         //newer version
    137.         RaycastHit2D hit = Physics2D.Raycast (firePointPosition, (mousePos - firePointPosition),100, whatLayerToHit);
    138.      
    139.         if (Time.time >= timeToSpawnFX) {
    140.             ShotFX ();
    141.             timeToSpawnFX =Time.time + FXspawnRate;
    142.             }
    143.         //ShotFX ();
    144.         //put in function to spawn the BulletTrailPrefab
    145.         //right here :P
    146.  
    147.         //show the Ray for testing purposes - Brackeys is using DrawLine for this - nil thios agam
    148.         //make ray go ToString edges of screen by using * 100
    149.         ////Debug.DrawLine (firePointPosition, (mousePosition - firePointPosition)*100, Color.cyan);
    150.         //Debug.DrawRay (firePointPosition, (mousePosition - firePointPosition), Color.green);
    151.         //newer version
    152.         Debug.DrawRay (firePointPosition, (mousePos - firePointPosition), Color.green);
    153.  
    154.  
    155.         //hit stuff this stuff is done away with
    156.         if(hit.collider != null){
    157.             Debug.DrawLine (firePointPosition, hit.point, Color.red);
    158.             //when ray hits on object on selected layermask make line red
    159.             //like the drawline code
    160.             //Debug.DrawRay (firePointPosition, (mousePosition - firePointPosition), Color.red);
    161.             //Debug.Log("We hit the: "+hit.collider.name+ "and did: "+hitDamage+ " damage!");
    162.  
    163.             }//end outer if
    164.              
    165.         }//end Shoot()
    166.  
    167.  
    168.  
    169.     //A 'void' function to create/instantiate the BulletTrailPrefab
    170.     //and MuzzleFlashPrefab and make them visible
    171.     //make
    172.     void ShotFX(){
    173.  
    174.         //play the sound???
    175.         audio.PlayOneShot(laserShot, 1.0f);
    176.  
    177.         //get bullet direction
    178.         // from PGJ
    179.         bulletDirection = (mousePos - firePointPosition).normalized;
    180.  
    181.         //GameObject go = Instantiate (bulletThingy, firePointPosition, Quaternion.identity) as GameObject;
    182.         go = Instantiate (bulletThingy, firePoint.position, firePoint.rotation) as GameObject;
    183.  
    184.  
    185.         //using Method Three as provided by: pgj
    186.         //stored in document: Bullet Movement.odt
    187.         //Directory:  This PC -> Documents
    188.         go.GetComponent<MoveTrail_V> ().SetDirection (bulletDirection);
    189.  
    190.  
    191.         Transform clon3 = Instantiate (MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
    192.         clon3.parent = firePoint;
    193.  
    194.         //set up random size for the 'muzzle flash'
    195.         float size = Random.Range (.6f, 1f);
    196.  
    197.         //don't need to worry about Z rotation
    198.         clon3.localScale = new Vector3(size, size, size);
    199.         Destroy (clon3.gameObject, .04f);
    200.  
    201.         }//end ShotFX
    202.  
    203.  
    204.  
    205. }//end class Weapons_V
    206.  
     
    Last edited: Aug 31, 2015
    theANMATOR2b likes this.
  4. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    Does anyone have any ideas as to what else I might try?