- Home /
iPhone: Bounce on touch
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.
Give me a few $$anonymous$$utes. Probably within 15 $$anonymous$$utes I will need help. Thank you so much though!
Answer by whydoidoit · Jun 19, 2012 at 05:17 PM
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;
Im still a bit confused on how to go about doing this. I understand generally what you are saying but I just need help on the base. So I would add a script on the ball saying if it is touched it will add force to the rigid body.
Answer by KaiserDE · Jun 19, 2012 at 10:12 PM
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?