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

How get the enemy velocity that shoots bullets?

Discussion in '2D' started by captnhanky, Mar 10, 2019.

  1. captnhanky

    captnhanky

    Joined:
    Dec 31, 2015
    Posts:
    97
    Hi!

    I want to take the enemy velocity into calculation for the speed of the bullets it shoots.
    How can I access the "owner" velocity from the bullet script?

    Thanks
    Andy
     
  2. milos_nov

    milos_nov

    Joined:
    Jun 2, 2017
    Posts:
    3
    I am guessing you have a bullet script and a enemy script.
    And I'm guessing you have the starting speed of the bullet.

    So what you want to do is when you Instantiate the bullet, you want the enemy shooting it to be the parent for a split second.
    So what you would do with the bullet script is something like this:

    Code (CSharp):
    1. float speed = 3;
    2.  
    3.     // Start is called before the first frame update
    4.     void Start()
    5.     {
    6.         speed = speed + gameObject.GetComponentInParent<Rigidbody2D>().velocity.x; //takes the speed of the owner
    7.         transform.parent = null; // will remove from the parent to avoid glitchy behaviour.
    8.     }
    This should work if you have multiple enemies.

    If it doesn't just add a custom timer so that it takes the speed first and detaches the bullet from the parent second.

    Cheers!
    And have fun making games!
     
    Last edited: Mar 10, 2019
  3. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    you can store the link to the bullet by spawning them and then change the needed public variable in this linked object
    void Shooting () {
    GameObject bullet = Instantiate (bulletPrefab, transform.position, transform.rotation);
    bullet.ownersSpeed = rb.velocity.x;
    }
     
  4. captnhanky

    captnhanky

    Joined:
    Dec 31, 2015
    Posts:
    97
    Thank you both!! ..this helped me a lot and I am understanding things better!!
     
    Last edited: Mar 10, 2019