Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity 2d jumping script

Does anyone have a good jumping script for 2d games in unity? The code I have works but still is far from jumping, it looks like it is flying.

using UnityEngine;
using System.Collections;

public class movingplayer : MonoBehaviour {

public Vector2 speed = new Vector2(10,10);

private Vector2 movement = new Vector2(1,1);

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    float inputX = Input.GetAxis ("Horizontal");
    float inputY = Input.GetAxis ("Vertical");

    movement = new Vector2(
        speed.x * inputX,
        speed.y * inputY);

    if (Input.GetKeyDown ("space")){
                         transform.Translate(Vector3.up * 260 * Time.deltaTime, Space.World);
                 } 

}
void FixedUpdate()
{
    // 5 - Move the game object
    rigidbody2D.velocity = movement;
    //rigidbody2D.AddForce(movement);

}
}
like image 983
user3189504 Avatar asked Aug 17 '14 15:08

user3189504


1 Answers

The answer above is now obsolete with Unity 5 or newer. Use this instead!

GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...

    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
    transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
    {
        GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.

Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)

like image 113
laszlar Avatar answered Oct 06 '22 09:10

laszlar