Reputation: 21
I am trying to make replica of stack jump game for learning. I am trying to make my player jump for fixed height but with below code, it always jumps at different height. If i touch for long then it jumps high and if i touch and release release immediately then it jumps very low. I want my player to jump constant height for long touch or for short touch both. I have just started learning unity. Please help!
Here is my code -
Touch touch;
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if ((touch.phase == TouchPhase.Began) && isGrounded)
{
//rb.velocity = Vector2.up * jumpForce;
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
isGrounded = false;
}
if (touch.phase == TouchPhase.Ended)
{
//rb.velocity = Vector2.down * jumpForce;
rb.AddForce(Vector2.down * jumpForce, ForceMode2D.Impulse);
isGrounded = true;
}
}
Upvotes: 0
Views: 825
Reputation: 1293
I had done exactly the same task when I was learning Unity. So what you have to do is to Add Component Rigitbody2D to your game object
private Rigidbody2D body;
private float jumpForce = 12.0f;
void Start()
{
body = GetComponent<Rigidbody2D>();
}
void Update()
{
bool grounded = false;
// set to true when your gameObject is on the ground
// Assume Space button is for jump
if(grounded && Input.GetKeyDown(KeyCode.Space))
{
body.AddForce(Vector2.up*jumpForce, ForceMode2D.Impulse);
}
}
So the idea is you jump when are are on the ground (you can use Physics2D.OverlapArea to detect collision with the ground), you can control how high you want to jump, and you do that using AddForce.
Upvotes: 1