How to use rigidbody.addforce for a bullet in a 2D game

user2737948 picture user2737948 · Feb 2, 2015 · Viewed 16.1k times · Source

I'm a beginner in unity and I want to recreate a 2D turn based game like worms. I have a turret and a bullet. The problem that I have is that I cant use this code because Im using colliders and rigidbodies in 2D, I checked in the documentation and there's a rigidbody.addforce in 2D but I don't understand how to use it. This question may be silly but bear with me.

using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
    public float speed;

    // Use this for initialization
    void Start () { 
        rigidbody.AddForce(5, 5, 0, ForceMode.Impulse);
    }

    // Update is called once per frame
    void Update () {
        transform.Translate(speed * Time.deltaTime, 0, 0);
    }

    void OnCollisionEnter(Collision c){
        if (c.gameObject.tag == "Platform") {
            Destroy(gameObject);
        }
    }
}

Answer

maZZZu picture maZZZu · Feb 2, 2015

Just change this:

    rigidbody.AddForce (5,5,0,ForceMode.Impulse);

to 2D equivalent:

    rigidbody2D.AddForce(new Vector2(5, 5), ForceMode2D.Impulse);

Also if you have 2D colliders attached to the gameObjects you need to use OnCollisionEnter2D instead of OnCollisionEnter

PS. If you want just the force to affect to the speed remove this line:

    transform.Translate(speed * Time.deltaTime, 0, 0);