- Home /
How do I instantiate and shoot a ball along a ray cast? [ANSWERED]
Hi Guys, Above is the GameObject that I am working on [IMAGE]. The balls fall into the catcher, and are destroyed when they hit the bottom of it (out of the players view).
My aim now is to instantiate a new ball behind the circular cannon and shoot it in the direction it is facing. (It is a separate GameObject that the user can rotate).
Any help would be greatly appreciated. Thank you!
Answer by BlackWingsCorp · May 07, 2013 at 03:40 PM
Hey add an empty gameobject (let's call it launcher) to the scene and make it a child of the gameobject that the user can rotate and reset it's transform values. Afterwards place the launcher at the tip of the canon in a way they don't collide together. when done open monodevelop and write something like this tell me how it works :
public Rigidbody ball;
public float speed = 200; //change it according to the desired speed
void Update(){
if(Input.GetButtonUp("Fire1"){//if the player clicks the left mouse button then releases
public Rigidbody newBall = Instantiate(ball, transform.position, transform.rotation);
newBall.velocity = transform.forward * speed;
Destroyer();
}
}
void Destroyer(){
yield new WaitForSeconds(2);//waits 2 seconds before destroying the newBall
Destroy(newBall.gameObject);
}
Thanks heaps! You're a great help. I changed a bit here and there, and this is what I ended up with.
public var firedBall:GameObject;
public var speed:float = 200; //change it according to the desired speed
function Update(){
ballShooter();
}
function ballShooter (){
yield WaitForSeconds(2);
if(GunBall$$anonymous$$iller.ballsReadyToBeShot>=1){
GunBall$$anonymous$$iller.ballsReadyToBeShot-=1;
var newObj = Instantiate(firedBall, transform.position, transform.rotation);
Globals.activeBalls++;
newObj.name="FiredBall";
newObj.velocity = transform.forward * speed;
}
}
Thanks!
If you are happy with his answer, click the checkmark next to the answer. This closes the question out and also gives karma to the person who answered your question.