1
\$\begingroup\$

I got the following code :

public ParticleSystem PS;
public GameObject origin;
public float thrust = 1.0f;
public GameObject bullet;
private GameObject _bullet;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0))
    {
        Debug.Log("Pressed left click.");
        PS.Play();
        _bullet = Instantiate(bullet, origin.transform.position, origin.transform.rotation);
        _bullet.GetComponent<Rigidbody2D>().AddForce(origin.transform.forward * thrust);
    }
}

Where everything is working except the AddForce, the bullet is just dropping out of my weapon. I've made some research and my script seems to be correct. The bullet has attached a circle collider and a rigidbody2D.

Update: This did not change anything :

_bullet.GetComponent<Rigidbody2D>().AddForce(origin.transform.forward * thrust, ForceMode2D.Impulse);

And this neither :

_bullet.GetComponent<Rigidbody2D>().velocity = origin.transform.forward * thrust;

It's weird, because all of these should work actually.

\$\endgroup\$
  • \$\begingroup\$ Adding a force is good for acceleration over time, like a rocket engine burning or a magnet pulling. For firing a bullet you usually want something more instantaneous, like setting the velocity directly or applying an impulse. Have you tried this? \$\endgroup\$ – DMGregory Oct 1 '16 at 13:49
  • \$\begingroup\$ Updated question \$\endgroup\$ – TobiasW Oct 1 '16 at 13:56
  • 1
    \$\begingroup\$ It could just be that your thrust is too low, or that the object is hitting something immediately that's sapping its momentum, or that there's another script in your project that's also trying to control the bullet and overriding this effect... \$\endgroup\$ – DMGregory Oct 1 '16 at 14:05
  • \$\begingroup\$ Thrust is on 10000 and there is no collider in range which could block it and just one script is using this :( It must be some stupid simple little thing I'm missing :/ \$\endgroup\$ – TobiasW Oct 1 '16 at 14:15
  • 1
    \$\begingroup\$ A 2D Game with transform.forward is not the best idea.... For sure transform.right is fixing the problem \$\endgroup\$ – TobiasW Oct 21 '16 at 6:35
2
\$\begingroup\$

There is just a minor mistake in this code which is transform.forward, which points to the z-axis which is obviously not working in a 2D game. So instead of this :

_bullet.GetComponent<Rigidbody2D>().AddForce(origin.transform.forward * thrust);

use this and it should work just fine :

_bullet.GetComponent<Rigidbody2D>().AddForce(origin.transform.right * thrust);

But at least the question is now a good summary of possible ways to give your object some speed. ( Force, velocity...)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.