1

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?

Alex
  • 1,172
  • 11
  • 31

1 Answers1

2

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.

CosmicGiant
  • 6,275
  • 5
  • 43
  • 58
  • I tried using `bullet.up` as the argument of `AddForce` but when I do that, there is only ever a y component of force added so the projectiles simply launch vertically from the tip regardless of the angle. – Alex Feb 26 '19 at 03:38
  • 1
    Nevermind, I just realized I should use the transform of the cannon or tip since I instantiate with identity rotation – Alex Feb 26 '19 at 03:40
  • 1
    @AlexEshoo It's not a bad idea to rotate the projectile to the source's (in this case `tip`'s) rotation on spawn. It won't make a visual difference in this case, since your projectile is a ball, but it will if you ever change it to an elongated shape like a cilinder (often used as a lit "tracer") or a bullet. It's a good habit, plus you can then base your direction on the projectile's forward direction, which is more readable/intuitive (you're not dealing with the source of the animore after the projectile is spawned). – CosmicGiant Feb 26 '19 at 03:46