Search Unity

How do I add in jumping to the Roll-A-Ball tutorial?

Discussion in 'Getting Started' started by sws90., Mar 7, 2015.

  1. sws90.

    sws90.

    Joined:
    Mar 7, 2015
    Posts:
    11
    Hello, I recently downloaded the personal edition of Unity 5, and followed the Roll-A-Ball tutorial to the end. I feel it's missing something, which is jumping.
    I can not figure out how to add it in, here is the code that I have for the Player object.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class Player : MonoBehaviour
    6. {
    7.     public float speed;
    8.     public GUIText countText;
    9.     private int count;
    10.     public GUIText wintext;
    11.  
    12.     void Start ()
    13.     {
    14.         count = 0;
    15.         SetCountText ();
    16.         wintext.text = "";
    17.     }
    18.  
    19.     void FixedUpdate ()
    20.     {
    21.         float moveHorizontal = Input.GetAxis("Horizontal");
    22.         float moveVertical = Input.GetAxis ("Vertical");
    23.      
    24.         Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
    25.      
    26.         GetComponent<Rigidbody>().AddForce (movement * speed * Time.deltaTime);
    27.  
    28. }
    29.     void OnTriggerEnter(Collider other)
    30.     {
    31.         if(other.gameObject.tag == "Pickup")
    32.         {
    33.             other.gameObject.SetActive(false);
    34.             count = count +1;
    35.             SetCountText ();
    36.     }
    37.     }
    38.  
    39.     void SetCountText ()
    40.     {
    41.         countText.text = "Count: " + count.ToString();
    42.         if (count >= 16)
    43.         {
    44.             wintext.text = "You Win!";
    45.  
    46.         }
    47.     }
    48. }
    I would like to be able to jump with the space bar.
    Any help is appreciated.
    Thanks :)
     
    Last edited: Mar 7, 2015
  2. CoolSpot

    CoolSpot

    Joined:
    Mar 7, 2015
    Posts:
    2
    I am new to Unity myself but I think if you either create a new movemnt trigger with a value in the y axis ( where it is currently 0.0f then it would cause the ball to jump. But I would know how to assign it to a key, just a guess ( if I am wrong I am sure someone will correct it). I am following the same tutorial, but got stuck at the
    Code (csharp):
    1. GetComponent<Rigidbody>().AddForce(movement *speed*Time.deltaTime);
    bit due to the change. Is the movement*speed*Time.deltaTime something you added in or was it necessary to make it work? if it was necessary do you have a link that explains it?

    Thanks
     
  3. Effervescent

    Effervescent

    Joined:
    Mar 7, 2015
    Posts:
    31
    Hi! I'm new to Unity and after reading your post I felt the same thing... so it started bothering me and I spent a bit of time trying to what CoolSpot suggested.

    I opened my old Roll The Ball project earlier and added the following in the Update() function:

    Please see EDIT below!
    Code (csharp):
    1. if (Input.GetKeyDown ("space")) {
    2.      Vector3 jump = newVector3 (0.0f, 200.0f, 0.0f);
    3.      GetComponent<Rigidbody>().AddForce (jump);
    4. }
    And it works just fine for me! xD The 200.0f was just a trial and error for me, I'm sure someone who knows physics can explain to you how to derive a reasonable value for it (1000.0f was too much and 10.0f was barely noticeable).

    It's worth noting that you can also jump while moving, too, and it doesn't stop you from moving in the direction you're already moving in before the jump. I think it's because the movement is added to the sphere as a force on it.

    I hope that works for you, too!


    EDIT:
    I tested it again and realised a big problem! With the script above you can actually jump when you are not actually touching the ground; as a result, you can fly if you keep pressing spacebar! This should help fix the problem assuming you are using the default y position from the tutorial, which is 0.5, if you don't intend to fly!

    Code (csharp):
    1. voidUpdate () {
    2.      if (Input.GetKeyDown ("space") && GetComponent<Rigidbody>().transform.position.y <= 0.5f) {
    3.      Vector3jump = newVector3 (0.0f, 200.0f, 0.0f);
    4.  
    5.      GetComponent<Rigidbody>().AddForce (jump)
    6.      }
    7. }
     
    Last edited: Mar 7, 2015
  4. sws90.

    sws90.

    Joined:
    Mar 7, 2015
    Posts:
    11
    Actually, Unity auto corrected it for me.
     
  5. sws90.

    sws90.

    Joined:
    Mar 7, 2015
    Posts:
    11
    That code seems like it would work, but I'm getting parsing errors for some reason. I tried to fix it, no luck.
     
    Last edited: Mar 7, 2015
  6. Effervescent

    Effervescent

    Joined:
    Mar 7, 2015
    Posts:
    31
    Oh. D: I wonder if it has anything to do with Unity 5? I updated to Unity 5 a couple of days ago and also let it auto-convert my script when I opened it earlier. I checked the tutorial video just now and I think it has to do with how the rigidbody component is called in Unity 5. If you are not using Unity 5, maybe you could try this:

    Code (csharp):
    1. voidUpdate () {
    2.      if (Input.GetKeyDown ("space") && rigidbody.transform.position.y <= 0.5f) {
    3.           Vector3jump = newVector3 (0.0f, 200.0f, 0.0f);
    4.  
    5.           rigidbody.AddForce (jump);
    6.      }
    7.  }

    if that doesn't fix the problem then I have absolutely no clue what's wrong. D:
     
  7. sws90.

    sws90.

    Joined:
    Mar 7, 2015
    Posts:
    11
    I am using unity 5.
    I'll continue trying to fix the parsing errors.

    Edit:

    I got it to work :D I had to make it a part of my FixedUpdate thing. Here's the code

    Code (CSharp):
    1. void FixedUpdate ()
    2.     {
    3.         float moveHorizontal = Input.GetAxis("Horizontal");
    4.         float moveVertical = Input.GetAxis ("Vertical");
    5.    
    6.         Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
    7.    
    8.         GetComponent<Rigidbody>().AddForce (movement * speed * Time.deltaTime);
    9.  
    10.         {
    11.             if (Input.GetKeyDown ("space") && GetComponent<Rigidbody>().transform.position.y <= 0.6250001f) {
    12.                 Vector3 jump = new Vector3 (0.0f, 200.0f, 0.0f);
    13.            
    14.                 GetComponent<Rigidbody>().AddForce (jump);
    15.             }
    16.         }
    17.    
    18.     }
    Thanks for all the help :)
    Now all I have to do is make the jump height into a float, so I can edit it in the editor. That should be easy enough.
     
    Last edited: Mar 7, 2015
    anees5588 likes this.
  8. U_nitty

    U_nitty

    Joined:
    Mar 8, 2015
    Posts:
    15
    Thanks for that - it's all helping the learning curve :)

    U_nitty
     
  9. Effervescent

    Effervescent

    Joined:
    Mar 7, 2015
    Posts:
    31
    Whaa! I completely missed your message because it came as an edit after I read that you're fighting with parsing errors! I'm glad that it worked out for you. To be honest, it's kind of exciting to know that there are other people out there working their way through the same problems that I have! I hope you have started thinking about your first small project!

    Good luck! It's amazing how much you can do in just a few days if you go through the tutorial diligently! I was already really happy after I learned how to make things move. d:
     
  10. sws90.

    sws90.

    Joined:
    Mar 7, 2015
    Posts:
    11
    I just figured out how to fix a minor bug. That being endless falling.

    Code (CSharp):
    1. void Update ()
    2.     {
    3.  
    4.         {
    5.             if (transform.position.y <= -10.0f)
    6.             {
    7.                 Application.LoadLevel (Application.loadedLevel);
    8.             }
    9.         }
    10.     }
    There's this edit to the code, if you wanted to restart with a button.

    Code (CSharp):
    1.  
    2.     void Update ()
    3.     {
    4.  
    5.         {
    6.             if (Input.GetKeyDown (KeyCode.R))
    7.             {
    8.                 Application.LoadLevel (Application.loadedLevel);
    9.             }
    10.         }
    11.     }
    Sadly, there's a bug with Application.LoadLevel (Application.loadedLevel); But can be fixed, more info can be found here http://forum.unity3d.com/threads/ap...-but-causes-light-intensity-to-change.308248/
     
  11. U_nitty

    U_nitty

    Joined:
    Mar 8, 2015
    Posts:
    15
    Struggling to learn C# here :(

    Are the braces at lines 5 and 10 above superflous ??

    U_nitty
     
  12. Effervescent

    Effervescent

    Joined:
    Mar 7, 2015
    Posts:
    31
    I believe they are. xD

    I'm not much of a programmer and it's difficult at the beginning. Just keep going through the tutorials and don't worry too much if you don't *remember* - personally, I find that it's fine as long as you can *recall* how to do things (and know where to look).

    At the beginning I force myself to do everything from scratch but it was silly because it actually slowed down the learning. Don't be ashamed of copy and pasting codes you've already typed during a tutorial and/or made yourself into a new project! o:

    Good luck!
     
  13. BlastOffProductions

    BlastOffProductions

    Joined:
    Jul 15, 2015
    Posts:
    13
    Here is a really good script I use. : )

    usingUnityEngine;
    usingSystem.Collections;

    publicclassWasdCont : MonoBehaviour {
    //Variables
    publicfloatspeed = 6.0F;
    publicfloatjumpSpeed = 8.0F;
    publicfloatgravity = 20.0F;
    privateVector3moveDirection = Vector3.zero;

    voidUpdate() {
    CharacterControllercontroller = GetComponent<CharacterController>();
    //isthecontrollerontheground?
    if (controller.isGrounded) {
    //FeedmoveDirectionwithinput.
    moveDirection = newVector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    moveDirection = transform.TransformDirection(moveDirection);
    //Multiplyitbyspeed.
    moveDirection *= speed;
    //Jumping
    if (Input.GetButton("Jump"))
    moveDirection.y = jumpSpeed;

    }
    //Applyinggravitytothecontroller
    moveDirection.y -= gravity * Time.deltaTime;
    //Makingthecharactermove
    controller.Move(moveDirection * Time.deltaTime);
    }
    }
     
  14. BlastOffProductions

    BlastOffProductions

    Joined:
    Jul 15, 2015
    Posts:
    13
    You might have to attach this as an other script.
     
  15. anees5588

    anees5588

    Joined:
    Jul 17, 2016
    Posts:
    3
    thankx alot mate
    this one really helped me
     
  16. dazelcrowe

    dazelcrowe

    Joined:
    Dec 22, 2016
    Posts:
    1
    ..i tried this but i get crazy ball rotating all the time and it is going through the ground...i have the character controller made and it is enveloping the ball and it is above the ground...the script is only good when i used kinematic but that is not what we are after here right?..can anyone help?...im totally new in unity scripting
     
  17. BlastOffProductions

    BlastOffProductions

    Joined:
    Jul 15, 2015
    Posts:
    13
    You might need to lower the speed. If it is too fast it will go crazy.
     
  18. Zambistical

    Zambistical

    Joined:
    Feb 16, 2017
    Posts:
    1

    I had the same issue

    I set the minimum move distance to 0 and removed the rigidbody component from the ball and that fixed it. hope this helps!
     
  19. jp8173

    jp8173

    Joined:
    Feb 24, 2017
    Posts:
    2
    can you not just use collide so like if collide with ground true then able to jump you would have to use different blocks so non child of same parent to do so right?
     
  20. soumyadip-k31

    soumyadip-k31

    Joined:
    Nov 23, 2015
    Posts:
    5
    I am stuck with the code and not able to make the ball jump!! pls, help me out! here is my code..

    using UnityEngine;
    using System.Collections;

    public class BallControl : MonoBehaviour {

    public float speed;
    private Rigidbody rB;


    void Start(){
    rB = GetComponent<Rigidbody> ();
    }

    void Update(){

    }

    void FixedUpdate(){
    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal,0.0f,moveVertical);

    rB.AddForce (movement*speed*Time.deltaTime);

    if(Input.GetKeyDown("space") && rB.transform.position.y<=0.6250001f){
    Vector3 jump = new Vector3 (0.0f,200.0f,0.0f);
    rB.AddForce (jump*Time.deltaTime);
    }

    }
    }
     
  21. pasitoi

    pasitoi

    Joined:
    Mar 28, 2017
    Posts:
    1
    @soumyadip-k31 change to this :
    rB.AddForce (jump);
     
    Schneider21 likes this.
  22. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    To expound upon what @pasitoi said, you do not need to apply Time.deltaTime to your forces inside FixedUpdate, as FixedUpdate is already running on the physics clock. Time.deltaTime is useful for when you want to do things inside the Update call, since Update may be called any number of times per frame, so multiplying by the time delta ensures consistent movement independent of your game's frame rate.
     
  23. bluevegas

    bluevegas

    Joined:
    Jun 16, 2017
    Posts:
    1
    I'm new to Unity & C# but I used to code in C+ a few years back. So excited to have found these demos and thought it was missing the pizzazz of spacebar JUMP too!!

    I found there is a lot of extra code that can be removed so it makes it easier to see how the code functions.
    Don't forget, you have already defined your ridgedbody to rb so the IF statement is the only new code addition needed to make your player object jump. I also cut back on that transform position so its slightly greater than your starting Y value (of .5)

    Code is below and placement can be seen in the attached screenshot

    I hope this helps my fellow codemonkeys :)

    if (Input.GetKeyDown("space") && rb.transform.position.y <= 0.51f)
    {
    Vector3 jump = new Vector3(0.0f, 200.0f, 0.0f);
    rb.AddForce(jump);
    }



    upload_2017-6-16_14-15-28.png
     

    Attached Files:

  24. FrankenCreations

    FrankenCreations

    Joined:
    Jun 14, 2017
    Posts:
    326
    I too struggled with jumping the roll a ball. It took me a week to get it right. A few things that i found while learning it.

    I started like everyone else just adding speed or force in the global up....worked ok

    I realised i needed a ground check or it would jump while in air or fly if you kept hitting jump. On Collison Stay didnt work because walls are collisions too I ended up with a raycast downward....worked ok

    I realised the ball always jumped straight up even if it was on a hill, no good, it needs to thake the surface its jumping from into account. I tried returning normals from the collision only to find they were the angle of the collision and not the angle of the face that was hit......more raycasting, averaging, fiddling, worked good.

    I thought i liked it, for a minute. Then I became annoyed because a quick tap and a ling press produced the same jump height, no good. So i did some lerping and the like to get it to maintain an arc instead of immediately stopping upward motion when the button was released. Now all is good, I am completely pleased with the result.

    What I learned was that things aren't as easy as first imagined. First day i thought i would just add some up force and 10 minutes later be jumping, not the case at all.
     
  25. BlitzEdge123

    BlitzEdge123

    Joined:
    Sep 14, 2017
    Posts:
    4
    Hello Everyone,
    I'm trying to find a simple jumping script and every time I come across a script it never seems to work. I fallow the instruction on everyone but come up empty handed. I'm trying to do this with out making an animated controller and scripting it. Like I said though my luck is running dry. I made a new character from scratch got the controls for the WASD to work just wish I could find the jumping script.
     
  26. BlitzEdge123

    BlitzEdge123

    Joined:
    Sep 14, 2017
    Posts:
    4
    Hello Everyone,
    So I even tried fallowing the scripts that have been posts on here but I ended up short again and don't know why I keep getting mono behavior end of line error as shown in the photo.
     

    Attached Files:

  27. FrankenCreations

    FrankenCreations

    Joined:
    Jun 14, 2017
    Posts:
    326
    You have an extra curly brace highlighted in orange. Its the brace that comes standard with the if statement. Then after your addforce line you have a set of braces. The set of braces should enclose the commands you want to have happen in your if statement. Braces come in pairs and it helps to indent and line them up so you can tell wich end brace belongs to which beginning brace.
     
  28. BlitzEdge123

    BlitzEdge123

    Joined:
    Sep 14, 2017
    Posts:
    4
    So Should I then move them to each corresponding line or delete them? Like move the bracket from line 27 to 28?
     
  29. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,145
    Remove the extra opening brace (the "{") after the part where you add the force to the rigidbody.
     
  30. BlitzEdge123

    BlitzEdge123

    Joined:
    Sep 14, 2017
    Posts:
    4
    Ok so I made a fresh script now I don't get that error but a new error. Unity really must hate me lol. Anyway this is the new error I get.
     

    Attached Files:

  31. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,145
    You're using the wrong symbol (an "," instead of an ";") at the end of the line above the line it's complaining about.
     
  32. FrankenCreations

    FrankenCreations

    Joined:
    Jun 14, 2017
    Posts:
    326
    Please also be aware that your jump script will only work if your ball is sitting on a level flat plane located at 0 on the y axis because of the way you check for ground. Your code basically says if the jump button is pushed and the ball is below 0.15 on the y axis then addforce of 200 in the global up direction. This will work to an extent on the tutorial project but if you start trying to build a game out of it you will have trouble.

    First off as stated above the ball will only jump if the surface its touching is located at or below 0.15 on the y axis. This means if you make a hill it wont jump from the ground above that point. It also means if your hill dips much below that point, for example -3 on the y axis, the ball will jump while in mid air without touching anything.

    Second, your ball will always jump straight up no matter what angle the surface it touches is at. This seems wrong when playing. If sitting on a sharp slope the ball should take that into account and jump at an angle relative to said slope.

    One final thing, your ball will always jump the same height. If you tap quikly you get a jump of 200. If you hold the jump input down you get a jump of 200. This is not usually how jump feels on a platformer. The longer you hold the jump the higher it should jump.

    Jumping seems simple at first but more goes into it that what you originally think. I went down the same path making the ball jump. I think its a good exercise and will help you get a handle on how some of the code side of things works. If you stick with it and get it just like you want it will help you on every game you make that has a character that can jump.

    My suggestion is to go through it in that order and by the end you will have a good grasp of jumping mechanics. First make it jump. Second make it jump from any ground not just level 0 height ground. Third make it take the angle of ground into account and then make the jump variable in height based on how long the user holds the jump command.

    I have been through this exact process recently as I am fairly new to this as well. I will keep a watch on this thread and help you get it figured out. I would just post the code I came up with but I'm curious to see how you approach it and I also think you will get more out of figuring it out than you would by just copying the code.
     
    Last edited: Sep 15, 2017