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);
}
}
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().
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