Search code examples
unity-game-engineprojectile

Trajectory of projectile slightly off Unity2D


I have a simple cannon I am trying to program to shoot a projectile. I have 4 game objects:

  • The tank object
  • A Pivot Object (child of tank)
  • A Cannon Object (child of pivot)
  • An empty GameObject called Tip which sits just above the cannon (child of cannon)

My code for the cannon object is below:

public class cannon: MonoBehaviour
{ 
    public float power = 1.0f;
    public Transform projectile;

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Transform bullet;
            Vector2 pos = transform.GetChild(0).position;
            bullet = Instantiate(projectile, pos, Quaternion.identity);
            Rigidbody2D bullet_rb = bullet.GetComponent<Rigidbody2D>();
            bullet_rb.AddForce(pos * power);
        }
    }
}

Everything seems to work okay, until I looked at the trajectory of the projectiles when the cannon is aimed directly along the x-axis. There is still a small y component to the applied force, which I didn't expect and do not desire.

Here's a gif:

enter image description here

What could be causing this behavior?


Solution

  • The force you're adding is pos (times a scalar power)... The position of your cannon is above zero on the y axis, so that's why it launches with a y offset. I'm assuming it has an x offset too, just less noticeable, because the base (tank) is centered at x while it's above center in the y. Try moving the whole tank setup off away from the scene root; you'll probably see a huge spike in the force of the projectile, because of this error of using pos.

    What you want is a vector representing a pure direction instead. One that is also normalized (magnitude of one). In this case, either right (forward in 2d) or up, from the perspective of the rotating tip or cannon.