- Home /
simple jump-script (2D)
I just started to make my first game with Unity - a simple Jump 'n Run. I used Rigidbody2D.AddForce
for the jump mechanic. Right now I can jump out of the window, if I hold the UpArrow
down. What I am looking for is an option to maximize the jump height. I tried to build a trigger-box and putting the jumping-script into an OnTriggerStay
-function, but this doesn't work. As I can't find an answer in the Manual, Scripting API or the internet I would appreciate some help :)
That's my current code:
public class Player : MonoBehaviour
{
public float moveSpeed;
public float jumpPower;
void Update ()
{
if (Input.GetKey(KeyCode.RightArrow))
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
if (Input.GetKey(KeyCode.LeftArrow))
transform.Translate(-Vector2.right * moveSpeed * Time.deltaTime);
Rigidbody2D rb = GetComponent<Rigidbody2D> ();
if (Input.GetKey(KeyCode.UpArrow))
rb.AddForce(Vector2.up * jumpPower);
}
}
What I found in the Scripting API was AddForce.impulse
. This sounds like what I am looking for. But unfortunately I am not able to implement it.
Not an answer to your question but just a quick tip. If you use a rigidbody2D, then don't use transform.Translate to move the object, use RigidBody2D.$$anonymous$$ovePosition ins$$anonymous$$d, since transform.Translate ignores physics but rigidbody2d.$$anonymous$$ovePosition produces collisions and triggers.
Answer by Andres-Fernandez · Jun 05, 2015 at 06:59 AM
This tutorial has great tips on making a 2D character controller you can apply. I suggest you use a grounded flag approach (using a boolean to check if the object is touching the ground and not allowing it to jump if it's not grounded).
Also check the Input.Get$$anonymous$$eyDown function to make the jump only once when you press the key.
Your answer
Follow this Question
Related Questions
[Solved] Having trouble with 2D Character Jump using Bolt 0 Answers
How can I change jump direction? 1 Answer
Problem with Jump 1 Answer
Rigidbody2D.MovePosition is not being instaneous 0 Answers
Jump Function C# hassle! 0 Answers