daily pastebin goal
53%
SHARE
TWEET

Untitled

a guest Mar 26th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using UnityEngine;
  2.  
  3. public class Ball : MonoBehaviour {
  4.  
  5.     //config params
  6.     [SerializeField] Paddle paddle1;
  7.     [SerializeField] float xPush = 2f;
  8.     [SerializeField] float yPush = 15f;
  9.     [SerializeField] AudioClip[] ballSounds;
  10.     [SerializeField] float randomFactor = 0.2f;
  11.  
  12.     //state
  13.     Vector2 paddleToBallVector;
  14.     private bool hasStarted = false;
  15.     Vector2 paddlePos;
  16.  
  17.  
  18.     // cached component references
  19.     AudioSource audioSource;
  20.     Rigidbody2D rb;
  21.  
  22.     // Start is called before the first frame update
  23.     void Start() {
  24.         paddleToBallVector = transform.position - paddle1.transform.position;
  25.         audioSource = GetComponent<AudioSource>();
  26.         rb = GetComponent<Rigidbody2D>();
  27.     }
  28.  
  29.     // Update is called once per frame
  30.     void Update() {
  31.         if (!hasStarted) {
  32.             LockBallToPaddle();
  33.             LaunchOnClick();
  34.         }
  35.     }
  36.  
  37.     private void LaunchOnClick() {
  38.         if (Input.GetMouseButtonDown(0)) {
  39.             hasStarted = true;
  40.             rb.velocity = new Vector2(xPush, yPush);
  41.         }
  42.     }
  43.  
  44.     private void LockBallToPaddle() {
  45.         paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
  46.         Debug.Log(paddlePos);
  47.         transform.position = paddlePos + paddleToBallVector;
  48.     }
  49.  
  50.     private void OnCollisionEnter2D(Collision2D collision) {
  51.         Vector2 velocityTweak = new Vector2(Random.Range(0f, randomFactor), Random.Range(0f, randomFactor));
  52.         if (hasStarted) {
  53.             AudioClip clip = ballSounds[Random.Range(0, ballSounds.Length)];
  54.             audioSource.PlayOneShot(clip);
  55.             rb.velocity += velocityTweak;
  56.         }
  57.     }
  58.  
  59.     public void Reset() {
  60.         hasStarted = false;
  61.         LockBallToPaddle();
  62.     }
  63.  
  64. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top