Created
August 21, 2015 00:12
-
-
Save joshalanwagner/4770cf2e6bd15dd440c5 to your computer and use it in GitHub Desktop.
Adjusting the x and y velocity of the ball.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using System.Collections; | |
| public class Ball : MonoBehaviour { | |
| public float margin = 1.5f; // don't want to be too controlling | |
| public float factor = 100f; | |
| private Paddle paddle; | |
| private bool hasStarted = false; | |
| private Vector3 paddleToBallVector; | |
| private Rigidbody2D rb; | |
| private float velocity = 6f; | |
| private float speed; | |
| private float dir; | |
| // Use this for initialization | |
| void Start () | |
| { | |
| rb = GetComponent<Rigidbody2D> (); | |
| paddle = GameObject.FindObjectOfType<Paddle>(); | |
| paddleToBallVector = this.transform.position - paddle.transform.position; | |
| } | |
| // Update is called once per frame | |
| void Update () | |
| { | |
| if (!hasStarted) | |
| { | |
| // lock ball to paddle | |
| this.transform.position = paddle.transform.position + paddleToBallVector; | |
| // wait for mouse click to launch | |
| if (Input.GetMouseButtonDown (0)) | |
| { | |
| print ("mouse clicked, launch ball"); | |
| hasStarted = true; | |
| this.rigidbody2D.velocity = new Vector2 (velocity, velocity); | |
| } | |
| } | |
| } | |
| void OnCollisionEnter2D (Collision2D other) | |
| { | |
| if (hasStarted) {audio.Play (); | |
| // adjust x: speed up , slow down | |
| speed = Mathf.Abs (rb.velocity.x); | |
| dir = Mathf.Sign (rb.velocity.x); | |
| if (speed < velocity - margin) {rb.AddForce (new Vector2 (dir * factor, 0));} | |
| if (speed > velocity + margin) {rb.AddForce (new Vector2 (-dir * factor, 0));} | |
| // adjust y: speed up , slow down | |
| speed = Mathf.Abs (rb.velocity.y); | |
| dir = Mathf.Sign (rb.velocity.y); | |
| if (speed < velocity - margin) {rb.AddForce (new Vector2 (0, dir * factor));} | |
| if (speed > velocity + margin) {rb.AddForce (new Vector2 (0, -dir * factor));} | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment