Search Unity

C# Jumping Problems. Rigidbody gives a strange error.

Discussion in 'Scripting' started by FritzPeace, Sep 15, 2014.

  1. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    In my program, I am trying to make my cube ,once I press spacebar, jump. the jump would include also a 180 degrees front flip. I did not find a solution. When I tried to use rigidbody I had a problem because it made the block rotate in a strange manner.

    What should I do to make it jump?
     
  2. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Do you have any of your axis locked?
     
  3. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    I am only using x axis. The block only goes in one direction
     
  4. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    So, what do you mean by "strange manner"? Describe what you are seeing and what you're supposed to see.
     
  5. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    I want the block to just move all the time in the x axis. It is doing this but once I add rigidbody, the block after some seconds goes to the left ( rotating ).
     
  6. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    So you don't want it to rotate at all? Lock rotation on the Z axis.
     
  7. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    How do I do this? and how do I make it jump :p?
     
  8. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    Okay. And how do I make it jump?
     
  9. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    Code (CSharp):
    1. //CameraMovement.cs
    2. //C#
    3. //
    4. //Comments:
    5. //    Changed LateUpdate to FixedUpdate, and changed relevant deltaTime value to fixedDeltaTime value
    6. //    Commented code for ease of understanding
    7. //
    8. using UnityEngine;
    9. using System.Collections;
    10. public class CameraMovement : MonoBehaviour
    11. {
    12.     public Transform target;        //object to follow
    13.     public float smoothing = 5.0f;    //motion smoothing
    14.  
    15.     private Vector3 offset;            //base offset of camera from object
    16.  
    17.     //use this to initialize component references and variables
    18.     void Awake()
    19.     {
    20.         offset = transform.position - target.position;    //calculate base offset
    21.     }
    22.  
    23.     //use this to intialize components and script references
    24.     void Start()
    25.     {
    26.     }
    27.  
    28.     //this runs every frame
    29.     void FixedUpdate()
    30.     {
    31.         Vector3 targetCamPos = target.position + offset;    //calculate camera position
    32.         //update camera position with smoothing
    33.         transform.position = Vector3.Lerp(transform.position, targetCamPos, smoothing * Time.fixedDeltaTime);
    34.     }
    35. }
    36.  
    Code (CSharp):
    1. //PlayerMovement.cs
    2. //C#
    3. using UnityEngine;
    4. using System.Collections;
    5.  
    6. [RequireComponent(typeof(Rigidbody))]
    7. public class PlayerMovement : MonoBehaviour
    8. {
    9.     public float jumpHeight;        //how high to jump
    10.     public float jumpTime;            //how long will the jump take to touch down
    11.     public float moveSpeed;            //how fast we move on X axis
    12.  
    13.     private bool jumping;            //state to determine whether we're jumping or walking/running
    14.     private float jumpTimer;        //timer to count seconds to perform jump for a period of time
    15.     private float jumpFrom;            //base offset of jump (starting Y position of player object)
    16.  
    17.     private Rigidbody _rigidbody;    //cache to our rigidbody component
    18.  
    19.     //use this to initialize component references and variables
    20.     void Awake()
    21.     {
    22.         _rigidbody = rigidbody;                //cache our rigidbody
    23.         jumping = false;                    //we don't want to start off jumping
    24.     }
    25.  
    26.     //use this to intialize components and script references
    27.     void Start()
    28.     {
    29.     }
    30.  
    31.     //this runs every frame (used for input checking)
    32.     void Update()
    33.     {
    34.         if (!jumping && Input.GetKeyDown(KeyCode.Space))
    35.         {//if we're not jumping, and we press the space key down
    36.             jumpTimer = 0.0f;                    //reset jumpTimer to 0.0f
    37.             jumping = true;                        //set jumping state
    38.             jumpFrom = _rigidbody.position.y;    //get the starting ground height for start of jump
    39.         }
    40.     }
    41.  
    42.     //use this for physics updates
    43.     void FixedUpdate()
    44.     {
    45.         if (jumping)
    46.         {//we're currently amidst jumping
    47.             jumpTimer += Time.fixedDeltaTime;    //count seconds
    48.             if (jumpTimer >= jumpTime)
    49.             {//jump elapsed
    50.                 jumpTimer = jumpTime;
    51.                 jumping = false;
    52.             }
    53.          
    54.             if (jumpTimer > (jumpTime * 0.5f) && Physics.Raycast(new Ray(_rigidbody.position, -Vector3.up), 0.51f))
    55.             {//if we're half way through the jump, find the ground, we're coming in for a landing
    56.                 jumping = false;    //if we find the ground before the jumpTimer elapses, elapse now
    57.                 _rigidbody.rotation = Quaternion.identity;    //reset rotation to zero (upright)
    58.             }
    59.             else
    60.             {//we're amidst a jump
    61.                 Vector3 curPos = _rigidbody.position;            //get our current position
    62.                 Vector3 moveDir = new Vector3(moveSpeed * Time.fixedDeltaTime, 0, 0);    //calculate X movement
    63.                 float t = (jumpTimer / jumpTime) * Mathf.PI;    //calculate theta for jump arc
    64.              
    65.                 curPos = new Vector3(curPos.x, jumpFrom + (Mathf.Sin(t) * jumpHeight), curPos.z);    //calculate jump offset for position
    66.                 _rigidbody.MovePosition(curPos + moveDir);        //move to the new position
    67.                 _rigidbody.rotation = Quaternion.Euler(0, 0, (jumpTimer / jumpTime) * -180.0f);        //calculate front flip roll
    68.             }
    69.          
    70.             if (!jumping) { jumpTimer = 0.0f; }    //jump elapsed, reset jumpTimer to 0.0f
    71.         }
    72.         else
    73.         {//we're walking/running
    74.             Vector3 curPos = _rigidbody.position;        //get current position
    75.             Vector3 moveDir = new Vector3(moveSpeed * Time.fixedDeltaTime, 0, 0);    //calculate X movement
    76.             _rigidbody.MovePosition(curPos + moveDir);    //move to the new position
    77.         }
    78.     }
    79. }
    80.  
    Set your rigidbody constraints to match the following:
    position X(lock) Y(unlock) Z(lock)
    rotation X(lock) Y(lock) Z(lock)

    Hope this helps! :)

    EDIT: make sure rigidbody gravity is enabled also.

    ~
    Another walk in the park.
     
    Last edited: Sep 15, 2014
  10. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    Thank you very much. Everything works smoothly! Just the landing after the rotation that is kind of hard. It jumps rotates and then hits the ground. Is this normal? And why does the camera look kind of blurry in far away objects?
     
  11. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    Well the sharp snap back to zero is because the jump flip can't account for short distance jumps, if you're jumping on the same level ground height it'll go straight, I could perhaps try and rewrite it so that it will work with platform jumps?
    As for why the camera looks blurry I'm not sure, do u have any filters(Image Effects) on the camera? or maybe the far away objects are being LOD mip mapped, which can cause the texture to blur.

    Hope this helps.

    ~
    Another walk in the park.
     
  12. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    I re-scaled everything and the jump is looking fine. I think is this LOD thing. Is there a way to fix it? And thank you again!
     
  13. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    Here's a better jump script anyhow, I always like to improve stuff that I make.

    Code (CSharp):
    1. //PlayerMovement.cs
    2. //C#
    3. using UnityEngine;
    4. using System.Collections;
    5.  
    6. [RequireComponent(typeof(Rigidbody))]
    7. public class PlayerMovement : MonoBehaviour
    8. {
    9.     public float jumpHeight;        //how high to jump
    10.     public float jumpTime;            //how long will the jump take to touch down
    11.     public float moveSpeed;            //how fast we move on X axis
    12.    
    13.     private bool jumping;            //state to determine whether we're jumping or walking/running
    14.     private float jumpTimer;        //timer to count seconds to perform jump for a period of time
    15.     private float jumpFrom;            //base offset of jump (starting Y position of player object)
    16.     private float jumpTo;            //base offset of jump (ending Y position of player object)
    17.    
    18.     private Rigidbody _rigidbody;    //cache to our rigidbody component
    19.    
    20.     //use this to initialize component references and variables
    21.     void Awake()
    22.     {
    23.         _rigidbody = rigidbody;                //cache our rigidbody
    24.         jumping = false;                    //we don't want to start off jumping
    25.     }
    26.    
    27.     //use this to intialize components and script references
    28.     void Start()
    29.     {
    30.     }
    31.    
    32.     //this runs every frame (used for input checking)
    33.     void Update()
    34.     {
    35.         if (!jumping && Input.GetKeyDown(KeyCode.Space))
    36.         {//if we're not jumping, and we press the space key down
    37.             jumpTimer = 0.0f;                    //reset jumpTimer to 0.0f
    38.             jumping = true;                        //set jumping state
    39.             jumpFrom = _rigidbody.position.y;    //get the starting ground height for start of jump
    40.            
    41.             //perform a raycast to find the jump landing point ground height
    42.             float doubleHeight = jumpHeight * 2.0f;
    43.             RaycastHit hit;
    44.             if (Physics.Raycast(new Ray(_rigidbody.position + (new Vector3(jumpTime, doubleHeight, 0)), -Vector3.up), out hit, doubleHeight))
    45.             {
    46.                 jumpTo = hit.point.y + 0.5f;
    47.             }
    48.             else
    49.             {
    50.                 jumpTo = jumpFrom + 0.5f;
    51.             }
    52.             //turn gravity off
    53.             _rigidbody.useGravity = false;
    54.         }
    55.     }
    56.    
    57.     //use this for physics updates
    58.     void FixedUpdate()
    59.     {
    60.         if (jumping)
    61.         {//we're currently amidst jumping
    62.             jumpTimer += Time.fixedDeltaTime;    //count seconds
    63.             if (jumpTimer >= jumpTime)
    64.             {//jump elapsed
    65.                 jumpTimer = jumpTime;
    66.                 jumping = false;
    67.             }
    68.            
    69.             if (jumpTimer > (jumpTime * 0.5f) && Physics.Raycast(new Ray(_rigidbody.position, -Vector3.up), 0.51f))
    70.             {//if we're half way through the jump, find the ground, we're coming in for a landing
    71.                 jumping = false;    //if we find the ground before the jumpTimer elapses, elapse now
    72.                 _rigidbody.rotation = Quaternion.identity;    //reset rotation to zero (upright)
    73.             }
    74.             else
    75.             {//we're amidst a jump
    76.                 Vector3 curPos = _rigidbody.position;            //get our current position
    77.                 Vector3 moveDir = new Vector3(moveSpeed * Time.fixedDeltaTime, 0, 0);    //calculate X movement
    78.                 float t = jumpTimer / jumpTime;    //calculate theta for jump arc
    79.                
    80.                 curPos = new Vector3(curPos.x, Mathf.Lerp(jumpFrom, jumpTo, Mathf.Clamp(t, 0.0f, 0.5f) * 2.0f) + (Mathf.Sin(t * Mathf.PI) * jumpHeight), curPos.z);    //calculate jump offset for position
    81.                 _rigidbody.MovePosition(curPos + moveDir);        //move to the new position
    82.                 _rigidbody.rotation = Quaternion.Euler(0, 0, (jumpTimer / jumpTime) * -180.0f);        //calculate front flip roll
    83.             }
    84.            
    85.             if (!jumping)
    86.             {//jump elapsed, reset jumpTimer to 0.0f and turn gravity back on
    87.                 jumpTimer = 0.0f;
    88.                 _rigidbody.useGravity = true;
    89.             }
    90.         }
    91.         else
    92.         {//we're walking/running
    93.             Vector3 curPos = _rigidbody.position;        //get current position
    94.             Vector3 moveDir = new Vector3(moveSpeed * Time.fixedDeltaTime, 0, 0);    //calculate X movement
    95.             _rigidbody.MovePosition(curPos + moveDir);    //move to the new position
    96.         }
    97.     }
    98. }
    99.  
    As for the LOD thing, if you select the textures in your project file hierarchy, then in the inspector you should see mip map options there. Hope this helps! :)

    ~
    Another walk in the park.
     
  14. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    This is only for Unity PRO Right? I do not have it. I do not want to use the pro today because I will use it by the time I do more complex projects.
     
  15. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    No Unity Indie also uses mip mapping, you want to try tweaking the filter mode and aniso levels of your textures. Also if you change the texture type to 2D/sprite that might help some things. Not really sure off hand myself cause I don't make 2D games myself.
     
  16. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    How do I create this Text?
    I have my UI Text created named ScoreText. Then I created this script and linked it to the ScoreText object.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ScoreScript : MonoBehaviour {
    5.  
    6.     public static int score;
    7.    
    8.    
    9.     public Text text;
    10.    
    11.    
    12.     void Awake ()
    13.     {
    14.         text = GetComponent <Text> ();
    15.         score = 0;
    16.     }
    17.    
    18.    
    19.     void Update ()
    20.     {
    21.         text.text = "Score: " + score;
    22.     }
    23. }
    Can you tell what to do or give me a clue without giving the whole text :D? I want to learn a bit by myself.
     
  17. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    If you look at the Text class in the Unity Documentation (Help -> Scripting Reference) type into the search box Text, click on the closest matching link, and bam, there's your documentation, a hint would be it's "text" field. Hope this helps! ;)
     
  18. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    Thanks I will try.
     
  19. FritzPeace

    FritzPeace

    Joined:
    Sep 15, 2014
    Posts:
    29
    Am I Getting Closer? What should I do now?
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class StageManager : MonoBehaviour
    5. {
    6.     public int score = 0;
    7.     public GUIText scoretext;
    8.    
    9.    
    10.     void Start()
    11.     {
    12.         scoretext = GUIText("ScoreText");
    13.     }
    14.    
    15.     void FixedUpdate()
    16.     {
    17.         if (score >= 0)
    18.         {
    19.             score += 1;
    20.         }
    21.  
    22.         scoretext.text = "Score" + score;
    23.  
    24.     }
    25.  
    26.                  
    27. }
     
  20. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    that's it, looks right, might want to use Update instead of FixedUpdate though, just a suggestion.