I am currently developing a game for the iPhone and I have a question. First of all, the game is a soccer ball juggling game. The ball starts in the air And is pushed down by gravity and the game ends if it touches the ground. I want to make a script so every time someone touches the ball it bounces up but like a 30 degree range of direction. Any help would be greatly appreciated.
-
From an Update() function use Physics.RayCast to see if the touch position intersects with the ball. Use Camera.main.ScreenPointToRay() passing the touch positions (if you are using more than one).
-
Decide on whether to do the ray case when the touch begins, or all the time and only do the ray cast if the touch phase fits your expected phase(s).
-
When you detect a hit you need to AddForce to the rigidbody attached to the ball. You can create a Vector3 of the lowest possible angle and the multiple a Quaternion that you make from a random rotate around whichever axis you need (maybe Z).
var q = Quaternion.Euler(0,0,Random.Range(0,30)); var forceDirection = q * startingVector;
Okay, I have almost got this working. Raycast now works and it successfully recognizes when I touch the ball. Now all I need to know is how to input the addforce.
Here is the code I’m using for the ray cast.
var particle : GameObject;
function Update () {
for (var i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
// Construct a ray from the current touch coordinates
var ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);
if (Physics.Raycast (ray)) {
// Create a particle if hit
Instantiate (particle, transform.position, transform.rotation);
}
}
}
}
How would I add the addforce to that code?
Here is the code I have for the addforce.
function FixedUpdate () {
rigidbody.AddForce (Vector3.up * 10);
}
How would I input that code into the previous one?