Created
June 14, 2018 16:28
-
-
Save dimmduh/e53fe04aa008a9380a91879c15919417 to your computer and use it in GitHub Desktop.
unity example - ball jump
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class Ball : MonoBehaviour | |
{ | |
private Rigidbody rb; | |
[Header("Jumping")] | |
public Vector3 jumpForce = Vector3.up; | |
public float jumpTimeout = 0.1f; | |
private bool nextJump; | |
private float nextJumpTime; | |
[Space(20)] | |
[Header("Grounded")] | |
public LayerMask groundMask; | |
public float groundCheckDistance = 0.1f; | |
private bool isGrounded; | |
private float halfHeight; | |
private float groundCheckRadius; | |
// Use this for initialization | |
void Start() | |
{ | |
rb = GetComponent<Rigidbody>(); | |
halfHeight = GetComponent<Renderer>().bounds.size.y / 2f; | |
groundCheckRadius = GetComponent<Renderer>().bounds.size.x / 4f; | |
} | |
// Update is called once per frame | |
void Update() | |
{ | |
HandleInput(); | |
if (isGrounded && nextJump && nextJumpTime < Time.time) | |
{ | |
Jump(); | |
nextJumpTime = Time.time + jumpTimeout; | |
} | |
} | |
private void HandleInput() | |
{ | |
if (Input.GetKeyDown(KeyCode.Space)) | |
{ | |
nextJump = true; | |
} | |
if (Input.GetKeyUp(KeyCode.Space)) | |
{ | |
nextJump = false; | |
} | |
} | |
void Jump() | |
{ | |
rb.AddForce(jumpForce, ForceMode.Impulse); | |
rb.velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z); | |
} | |
private void FixedUpdate() | |
{ | |
CheckGround(); | |
} | |
void CheckGround() | |
{ | |
RaycastHit hit; | |
isGrounded = Physics.SphereCast(transform.position, groundCheckRadius, Vector3.down, out hit, groundCheckDistance + halfHeight - groundCheckRadius, groundMask); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment