Skip to content

Instantly share code, notes, and snippets.

@JackDraak
Last active February 12, 2016 01:44
Show Gist options
  • Save JackDraak/8615ed8856ae7a7e8344 to your computer and use it in GitHub Desktop.
Save JackDraak/8615ed8856ae7a7e8344 to your computer and use it in GitHub Desktop.
Example of constraining ball velocity
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public AudioClip ball;
private float currentVelocityX;
private float currentVelocityY;
//...
private LevelManager levelManager;
private float maxVelocityX = 13f;
private float maxVelocityY = 19f;
private Paddle paddle;
private Vector3 paddleToBallVector;
private Vector2 preClampVelocity;
void InitializeBallState () {
paddleToBallVector = this.transform.position - paddle.transform.position;
// 0.7f = 70% of "speedLimit" is all that we let X get, to limit lateral bouncing
maxVelocityX = (0.7f * (PlayerPrefsManager.GetSpeed () + 0.01f) * maxVelocityX);
// 1.18f = 118% of "speedLimit" goes to Y.. encouraging vertical velocity
maxVelocityY = (1.18f * (PlayerPrefsManager.GetSpeed () + 0.05f) * maxVelocityY);
// NOTE the +0.01, and +0.05 are there for my slowest setting to still have enough energy to hit to upper boundary
// probably something to not use on your first go
}
// this is here for two purposes. 1: clamp velocity. 2: prevent bounce-looping with some random bounce jarring
void OnCollisionEnter2D(Collision2D collision) {
Vector2 tweak = new Vector2 (Random.Range(-0.25f, 0.25f), Random.Range(-0.15f, 0.15f));
if (levelManager.HasStartedReturn()) {
AudioSource.PlayClipAtPoint (ball, transform.position); // optional 3rd float value for volume
preClampVelocity = (GetComponent<Rigidbody2D>().velocity += tweak);
currentVelocityX = Mathf.Clamp (preClampVelocity.x, -maxVelocityX, maxVelocityX);
currentVelocityY = Mathf.Clamp (preClampVelocity.y, -maxVelocityY, maxVelocityY);
GetComponent<Rigidbody2D>().velocity = new Vector2 (currentVelocityX, currentVelocityY);
}
}
void Start () {
levelManager = GameObject.FindObjectOfType<LevelManager>(); if (!levelManager) Debug.LogError (this + ": unable to attach to LevelManager");
paddle = GameObject.FindObjectOfType<Paddle>(); if (!paddle) Debug.LogError (this + ": unable to attach to Paddle");
InitializeBallState();
}
void Update () {
// lock ball (relative) to paddle if game !started || ballDropped
if (!levelManager.HasStartedReturn()) {
this.transform.position = paddle.transform.position + paddleToBallVector;
// launch the ball and begin play on mouse-click
if (Input.GetMouseButtonDown(0)) {
levelManager.HasStartedTrue();
this.GetComponent<Rigidbody2D>().velocity = new Vector2 (Random.Range(-12f, 12f), Random.Range(8f, 10f));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment