Search Unity

[Solved] Trying to set velocity of a tank projectile

Discussion in 'Physics' started by Polzunov, Jan 21, 2019.

  1. Polzunov

    Polzunov

    Joined:
    Aug 31, 2017
    Posts:
    3
    I have a pretty simple tank object, which consists from nested tank, chassis, turret and muzzle at the end of the turret. I`m trying to fire a projectile from muzzle with this code:

    Code (CSharp):
    1. var projectile = Instantiate(projectilePrefab, muzzle.transform.position, muzzle.transform.rotation);
    2. projectile.GetComponent<Rigidbody2D>().AddForce(muzzle.transform.position, ForceMode2D.Impulse);
    If tank stays steady and looks to the up, projectile slowly fires in right direction. If I rotate whole tank, it fires right too. If i rotate turret also, projectiles start diverge from the trajectory i expect. If I move tank and fire, projectiles start to fly to some weird random directions.

    May be there is some more right way to give projectile velocity 10 in the direction of muzzle, and add current tank speed to this direction also?
     
  2. Jichaels

    Jichaels

    Joined:
    Dec 27, 2018
    Posts:
    237
    I'm doing something quit similar but with a gun and it works fine. Try :

    projectile.GetComponent<Rigidbody2D>().AddForce(muzzle.transform.forward);
     
  3. Polzunov

    Polzunov

    Joined:
    Aug 31, 2017
    Posts:
    3
    The projectile remains stationary after this line, as if no force was applied at all. The good news is that it remains directed where it is supposed to be.
     

    Attached Files:

  4. Jichaels

    Jichaels

    Joined:
    Dec 27, 2018
    Posts:
    237
    You could try adding more force (multiplying the transform.forward) or use a different ForceMode. Base ForceMode depends on the mass I believe
     
  5. Polzunov

    Polzunov

    Joined:
    Aug 31, 2017
    Posts:
    3
    Thank you, problem is solved, this code finally works. Right direction was "muzzle.transform.up":

    Code (CSharp):
    1. var projectile = Instantiate(projectilePrefab, muzzle.transform.position, muzzle.transform.rotation);
    2. projectile.GetComponent<Rigidbody2D>().AddForce(muzzle.transform.up * projectileSpeed, ForceMode2D.Impulse);