Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Can't get my character to jump in 2D ( Unity 5 )

Discussion in 'Scripting' started by timoshaddix, May 24, 2015.

  1. timoshaddix

    timoshaddix

    Joined:
    Jan 7, 2014
    Posts:
    64
    Hello,

    I'm quite new into c# and Unity.
    I've managed to let me character move, now i was looking around the internet to let my character jump.
    I've read through alot of scripts but i couldn't manage to let a single one work.
    I got a script without compile errors but it's not jumping, it's not even going up or make any kind of movement ( it does move left and right )

    What am i doing wrong?

    This is my script:
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class PlayerMovement : MonoBehaviour {
    6.  
    7.     public float Speed = 1;
    8.     public float JumpHeight = 5;
    9.  
    10.     // Update is called ornce per frame
    11.     void Update () {
    12.     if (Input.GetKey(KeyCode.D))
    13.         {
    14.             transform.Translate(Vector2.right * Time.deltaTime * Speed);
    15.             transform.eulerAngles = new Vector2(0, 0);
    16.         }
    17.    
    18.     if (Input.GetKey(KeyCode.A))
    19.         {
    20.             transform.Translate(Vector2.right * Time.deltaTime * Speed);
    21.             transform.eulerAngles = new Vector2(0, 180);
    22.         }
    23.     if (Input.GetKeyDown(KeyCode.W))
    24.         {
    25.             gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * Time.deltaTime * JumpHeight);
    26.         }
    27.  
    28. }
    29. }
    30.  
    31.  
    I hope someone would be able to help me out.

    Thanks in advance!
     
    Last edited: May 24, 2015
  2. Nitugard

    Nitugard

    Joined:
    May 10, 2015
    Posts:
    343
    Replace this line:
    Code (CSharp):
    1. GetComponent<Rigidbody2D>.AddForce(Vector2.up * Time.deltaTime * JumpHeight);
    with this:
    Code (CSharp):
    1. gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * Time.deltaTime * JumpHeight);
    Hope it helped!
     
  3. timoshaddix

    timoshaddix

    Joined:
    Jan 7, 2014
    Posts:
    64
    I've got it working!, i removed Time.deltaTime and it jumped, apparently it was moving, but really really slow.
    Thanks for the help tho.