- Home /
Jumping irregularities
I have a script that makes a ball jump when the user taps the screen. The problem I have now is that if I tap the screen, everything works fine, but if I hold my finger on the screen the ball continues to rise as long as I hold my finger. How can I limit that? Also, how can I limit the total number of taps to, say two? Additionally, (sorry for this many questions) I have two codes that make sense to me, but only one works. I'm looking for some code clarity.
Why does
if (fingerCount > 0) dir.y = -Input.acceleration.x*.5; transform.position.y += dir.y; }
work, but
if (fingerCount > 0) rigidbody.AddRelativeForce (Vector3.up * jumpStrength); }
does not work?
Thanks for your assistance and getting through this whole thing.
Answer by zazery · Apr 13, 2012 at 08:32 AM
The reason why the ball continues to rise when you touch the screen is the condition for your if-statement will always be true since Input.touchCount will be > 0. Instead you want to perform the jump code only the first time you first touch the screen.
The best way to do this is check if the finger's phase is TouchPhase.Began. It looks like you're using Javascript so I wrote the example in it.
function Update ()
{
var fingerCount : int = 0;
for (var touch : Touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
fingerCount++;
}
// Your code here
}
Alternatively, a more naive approach but perhaps easier to understand is to use a boolean that is reset when the user stops touching the screen.
var firstTouch : boolean = true;
function Update()
{
if (firstTouch && Input.touchCount > 0)
{
firstTouch = false;
// your jump code here without the if-statement
}
if (Input.touchCount == 0)
firstTouch = true;
}
There are many possible reasons for why rigidbody.AddRelativeForce is not working. Check to see if you have a rigidbody attached to the sphere and isKinematic is unchecked. Make sure jumpStrength is large enough. I made it work by creating a default sphere with a rigidbody and jumpStrength set to 100.
Your best bet is to use rigidbody since changing transform.position does not implement physics or more importantly handle collision detection. An alternative approach is to use a CharacterController if you want more control than the physics engine provides but you will have to write the code to keep track of and compute velocity and acceleration. Read more about it in the Unity manual.
Your answer
Follow this Question
Related Questions
Jump Script for 2D (JavaScript) 0 Answers
Jumping with touch input. 0 Answers
Jump heights are different on different devices 0 Answers
Moving forward whilst jumping 3 Answers
Physics on a Ball 1 Answer