Skip to content

Instantly share code, notes, and snippets.

@Notoh
Last active July 19, 2022 15:11
Show Gist options
  • Save Notoh/a6e20a39be9a88fcf6b16e5c16cffdd9 to your computer and use it in GitHub Desktop.
Save Notoh/a6e20a39be9a88fcf6b16e5c16cffdd9 to your computer and use it in GitHub Desktop.
Unity Ball Rolling/Jumping C# Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RollingScript : MonoBehaviour {
public float rotationSpeed = 25.0F;
public float jumpHeight = 8.0F;
private bool isFalling = false;
private Rigidbody rigid;
void Start () {
rigid = GetComponent<Rigidbody> ();
}
void Update () {
//Handles the rotation of the ball
float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
rotation *= Time.deltaTime;
if (rigid != null) {
//Apply rotation
Vector3 vector = new Vector3(rotation,0.0F,0.0F);
rigid.AddForce (vector, ForceMode.Impulse);
if (UpKey() && !isFalling) {
//Jump
rigid.AddForce (Vector3.up * jumpHeight, ForceMode.Impulse);
}
}
}
public void OnCollisionStay (Collision col) { //Takes parameter of Collision so unity doesn't complain
isFalling = false;
}
public void OnCollisionExit() {
isFalling = true;
}
private bool UpKey() {
return (Input.GetKeyDown (KeyCode.W) || Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment