Skip to content

Instantly share code, notes, and snippets.

@zerosalife
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerosalife/79e76842d317b45a8415 to your computer and use it in GitHub Desktop.
Save zerosalife/79e76842d317b45a8415 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public float maxHeight;
public float minHeight;
public float timeToReachMaxHeight;
private float jumpVelocity;
private float gravity;
private float terminationVelocity;
private Vector3 pos;
private bool onPlatform = false;
private float velocity;
public void Start() {
velocity = 0f;
gravity = (2 * maxHeight) / Mathf.Pow(timeToReachMaxHeight, 2f);
jumpVelocity = Mathf.Sqrt(2 * gravity * maxHeight);
terminationVelocity = Mathf.Sqrt(Mathf.Pow(jumpVelocity, 2f) + 2 * gravity * (maxHeight - minHeight));
}
public void Update() {
// Debug.Log(velocity);
pos = transform.position;
if(Input.GetKeyDown("space")) {
Jump();
}
pos.y = pos.y + Time.deltaTime * velocity;
transform.position = pos;
if(!onPlatform) {
velocity = velocity - Time.deltaTime * gravity;
}
if(velocity > 0) {
velocity = Mathf.Min(terminationVelocity, velocity);
}
}
public void Jump() {
velocity = jumpVelocity;
onPlatform = false;
}
public void Stop(float top) {
pos = transform.position;
pos.y = top;
velocity = 0f;
transform.position = pos;
onPlatform = true;
}
}
using UnityEngine;
using System.Collections;
public class Platform : MonoBehaviour {
public GameObject ball;
private float top;
public void Start() {
top = transform.position.y;
}
void OnTriggerEnter(Collider other) {
if(other.transform.position.y > top) {
ball.SendMessage("Stop", top + 1f);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment