- Home /
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);
}
}
Answer by Raddeo · Aug 03, 2015 at 06:05 PM
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().
Answer by $$anonymous$$ · Aug 04, 2015 at 04:12 AM
I edited the code, but it doesn't work :(
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
Your answer
![](https://koobas.hobune.stream/wayback/20220611234244im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Drag a rigidbody2D around scene 2 Answers
Add force once when object is created 1 Answer
Android touch input 3 Answers
Code compiled to android platform behaves differently. 0 Answers
How to touch a specific cube 1 Answer