- Home /
Projectile motion with angle and force in one direction
EDIT
Figured it all out.
ORIGINAL
I am trying to make a simple game where there is a GUI with two text fields and a button ... player enters in angle and force into the two text areas and presses the button to launch an object forward (in x-direction) with player defined angle and force.
I running into a few problems. First off here is what I have so far:
var force:int; var angle:int; //var prefabBanana:Transform; var temp:int; var temptwo:int; var prefabBanana : GameObject; //var gorilla : GameObject; var elevationAngle : Vector3; var throwForce : int;
function OnGUI () {
if(GUI.Button(Rect(10, 50, 80, 20), "Launch!!")) {
Launch();
}
var text = GUI.TextField(Rect(10, 10, 50, 20), angle.ToString());
var texttwo = GUI.TextField(Rect(10, 30, 50, 20), force.ToString());
if (int.TryParse(text, temp)){
angle = Mathf.Clamp(0, temp, 360);
}
else if (text == "") angle = 0;
if (int.TryParse(texttwo, temptwo)){
force = Mathf.Clamp(0, temptwo, 360);
}
else if (texttwo == "") force = 0;
}
function Launch() {
elevationAngle = Vector3(angle,0,0);
throwForce = force;
var banana : GameObject = Instantiate(prefabBanana, transform.position, Quaternion.identity);
var elevation : Vector3 = Quaternion.Euler(elevationAngle) * transform.forward;
new banana.rigidbody.AddForce(elevation * throwForce);
}
I getting this error when I attempt to launch the object:
"InvalidCastException: Cannot cast from source type to destination type. fire.Launch () (at Assets/fire.js:40) fire.OnGUI () (at Assets/fire.js:15)
Nothing happens, the object is never launched, but the game runs fine and the script compiles fine.
Any ideas on what is wrong? Sorry I am not the best programmer out there!!
Thanks!!
Answer by KeithK · Apr 07, 2011 at 08:01 PM
In your Launch() function, try declaring your banana on a separate line, and defining it on the next line.
var banana : GameObject;
banana = Instantiate(prefabBanana, transform.position, Quaternion.identity);
I'm not a JavaScript developer. So if this works, I cannot explain why it needs to be done like that. Hopefully a JS guru can come explain it. =)
Not quite ...
I am starting to think my problem is with the object I have it attached to.
Your answer
![](https://koobas.hobune.stream/wayback/20220613121429im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Is this a problem of unity 3 or i am doing something wrong. 1 Answer
Show "Score:5" on my screen, how? 1 Answer
A job task : Projectile Motion 0 Answers
Simple projectile motion with wind 0 Answers
Finding angle of angular motion 1 Answer