- Home /
Create a ball then launch it
I am trying to instantiate a ball then launch it. Here is my current scrip
var ball : GameObject;
function Start () {
}
function Update () {
if(Input.GetKeyDown(KeyCode.Space)){
var create : GameObject = Instantiate(ball, transform.position, transform.rotation);
}
}
My problem is I don't know how to launch. Don't understand how I would add force to the ball after it is created.
Answer by ninjaboynaru · Jul 20, 2012 at 05:04 PM
Thanks guys for all your help but I finally figured it out.
create.rigidbody.AddForce(Vector3(0,0,500));
This did the trick and the ball went forward. I am still curios as why Seth Bergman's answer came up with an error
I was actually on my way to provide the answer you just posted, The reason Seths answer did not work was because he was trying to add to the velocity variable of the transform itself. A Transform component does not have a velocity, it simply holds the rotation position and scale information of a GameObject.
You can see that in the reference link he sent it is adding to the velocity variable of a rigidbody component using the transform components direction.
yep sorry, I was sloppy tired... rigidbody handles physics, as a rule.. replacing "transform" with "rigidbody" would make that work, careless of me
Answer by Seth-Bergman · Jul 20, 2012 at 05:48 AM
you can access the game object through the var create. you could add the line:
create.transform.velocity = transform.TransformDirection (Vector3.forward * 10);
as seen in the Script reference HERE
so:
var ball : GameObject;
function Start () {
}
function Update () {
if(Input.GetKeyDown(KeyCode.Space)){
var create : GameObject = Instantiate(ball, transform.position, transform.rotation);
//create.transform.velocity = transform.TransformDirection (Vector3.forward * 10);
create.rigidbody.velocity = transform.TransformDirection (Vector3.forward * 10);
//fixed careless mistake...
}
}
I tried your script, but an error occurs that says velocity is not a member of transform.
Answer by sam32x · Jul 20, 2012 at 06:25 AM
put a new script on the ball that says
function Update () {
transform.Translate(Vector3.forward * Time.deltaTime * 20);
}
then the ball will move forwards at 20 units per second. if the ball goes the wrong way then change the forwards to left or up or something. if you want the ball to go faster/slower change the 20 to something else, but if you make it go too fast it wont collide properly with other objects.
the guy above me has a better way though, because my way means it keeps moving forever.
Your answer
Follow this Question
Related Questions
Instantiated object don't recognize MouseClick. 0 Answers
Instantiate A Prefab 1 Answer
Error when trying to instantiate 1 Answer
Checking if object intersects? 1 Answer
Accessing Script on instated prefab 1 Answer