Skip to content

Instantly share code, notes, and snippets.

@Ciberusps
Forked from Priler/CubeController.cs
Created August 2, 2021 09:58
Show Gist options
  • Save Ciberusps/cd506172d18f8fd6ecea41e53dce7c56 to your computer and use it in GitHub Desktop.
Save Ciberusps/cd506172d18f8fd6ecea41e53dce7c56 to your computer and use it in GitHub Desktop.
JumpController.cs
using UnityEngine;
using DG.Tweening;
public class JumpController : MonoBehaviour
{
[SerializeField] private float _moveSpeed = 15f;
[SerializeField] private float _jumpForce = 30f;
[SerializeField] private Transform _cubeObjectTF;
[SerializeField] private float _fallMultiplier = 10f;
[SerializeField]
[Range(1, 360)]
private int _spinAnimationAngle = 180;
[SerializeField]
[Range(0.1f, 1.0f)]
private float _spinAnimationTime = 0.75f;
private Rigidbody _rb;
private bool _doJump = false;
private bool _isJumping = false;
void Awake()
{
_rb = transform.GetComponent <Rigidbody>();
}
void Update() {
if(Input.GetButtonDown("Jump") && !_isJumping) {
Jump();
}
}
// FixedUpdate is called once per Fixed Timestep (50 times/second default)
void FixedUpdate()
{
Vector3 moveVect = Vector3.forward * _moveSpeed * Time.deltaTime;
_rb.MovePosition(transform.position + moveVect);
if(_doJump) {
_rb.AddForce(Vector3.up * _jumpForce, ForceMode.Impulse);
_doJump = false;
}
// gravity fall multiplier
_rb.velocity += Vector3.up * Physics.gravity.y * (_fallMultiplier - 1) * Time.deltaTime;
}
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.CompareTag("Ground")) {
if(Input.GetButton("Jump") && _isJumping) {
// Bunny Hop
Jump();
} else if(_isJumping) {
_isJumping = false;
}
}
}
void Jump() {
_doJump = true;
_isJumping = true;
_cubeObjectTF.DOComplete();
_cubeObjectTF.DORotate(new Vector3(_spinAnimationAngle, 0, 0), _spinAnimationTime, RotateMode.LocalAxisAdd).SetRelative(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment