Shooting a cannon ball

Hi guys, I have a script, which instanciate a RigidBody2D cannon ball, and another one (attached to ball) which should fire the ball along the y axis. The fire script doesn’t work. Here it’s mine:

using UnityEngine;
using System.Collections;

public class BallFire : MonoBehaviour {

	public int speed;

	// Use this for initialization
	void Update () {

		Vector3 fireDir = new Vector3 (this.transform.position.x, this.transform.position.y);
		fireDir.Normalize ();
		this.GetComponent<Rigidbody2D> ().AddForce (fireDir * speed, ForceMode2D.Impulse);
	}
}

I believe that this line is a problem

Vector3 fireDir = new Vector3 (this.transform.position.x, this.transform.position.y);

You’re using Vector3 and then giving only two arguments. You just need to use Vector2. What’s more, you shouldn’t use this in Update() function. As it’s connected with physics, rigidbodies and force you should use it in FixedUpdate().

I edited the code, but it doesn’t work :frowning:

using UnityEngine;
using System.Collections;

public class BallFire : MonoBehaviour {

	public int speed;

	// Use this for initialization
	void Start () {

		Vector2 fireDir = new Vector2 (this.transform.position.x, this.transform.position.y);
		fireDir.Normalize ();
		this.GetComponent<Rigidbody2D> ().AddForce (fireDir * speed, ForceMode2D.Impulse);
	}
}

I change Update to Start, because i want fire the ball when I instance it