Skip to content

Instantly share code, notes, and snippets.

@jamesballard
Created February 21, 2016 02:34
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 jamesballard/74dfe29ff9dcaa8a909f to your computer and use it in GitHub Desktop.
Save jamesballard/74dfe29ff9dcaa8a909f to your computer and use it in GitHub Desktop.
Unity Bouncing Ball
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
private Paddle paddle;
private Vector3 paddleToBallVector;
private bool hasStarted = false;
// Constant speed of the ball
private float speed = 10f;
// Keep track of the direction in which the ball is moving
private Vector2 velocity;
// used for velocity calculation
private Vector2 lastPos;
// Use this for initialization
void Start () {
paddle = GameObject.FindObjectOfType<Paddle>();
paddleToBallVector = this.transform.position - paddle.transform.position;
}
// Update is called once per frame
void Update () {
if (!hasStarted) {
// lock the ball relative to the paddle until mouse press launch.
this.transform.position = paddle.transform.position + paddleToBallVector;
}
if (Input.GetMouseButtonDown (0)) {
print("Lauch Ball");
this.GetComponent<Rigidbody2D>().velocity = new Vector2(2f,10f);
hasStarted = true;
}
}
void OnCollisionEnter2D (Collision2D collision) {
if (hasStarted) {
//GetComponent<AudioSource> ().Play ();
// Normal
Vector3 N = collision.contacts[0].normal;
//Direction
Vector3 V = velocity.normalized;
// Reflection
Vector3 R = Vector3.Reflect(V, N).normalized;
// Assign normalized reflection with the constant speed
GameObject.FindObjectOfType<Ball>().GetComponent<Rigidbody2D>().velocity = new Vector2(R.x, R.y) * speed;
}
}
void FixedUpdate () {
// Get pos 2d of the ball.
Vector3 pos3D = transform.position;
Vector2 pos2D = new Vector2(pos3D.x, pos3D.y);
// Velocity calculation. Will be used for the bounce
velocity = pos2D - lastPos;
lastPos = pos2D;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment