Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class Ball : MonoBehaviour {
- //config params
- [SerializeField] Paddle paddle1;
- [SerializeField] float xPush = 2f;
- [SerializeField] float yPush = 15f;
- [SerializeField] AudioClip[] ballSounds;
- [SerializeField] float randomFactor = 0.2f;
- //state
- Vector2 paddleToBallVector;
- private bool hasStarted = false;
- Vector2 paddlePos;
- // cached component references
- AudioSource audioSource;
- Rigidbody2D rb;
- // Start is called before the first frame update
- void Start() {
- paddleToBallVector = transform.position - paddle1.transform.position;
- audioSource = GetComponent<AudioSource>();
- rb = GetComponent<Rigidbody2D>();
- }
- // Update is called once per frame
- void Update() {
- if (!hasStarted) {
- LockBallToPaddle();
- LaunchOnClick();
- }
- }
- private void LaunchOnClick() {
- if (Input.GetMouseButtonDown(0)) {
- hasStarted = true;
- rb.velocity = new Vector2(xPush, yPush);
- }
- }
- private void LockBallToPaddle() {
- paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
- Debug.Log(paddlePos);
- transform.position = paddlePos + paddleToBallVector;
- }
- private void OnCollisionEnter2D(Collision2D collision) {
- Vector2 velocityTweak = new Vector2(Random.Range(0f, randomFactor), Random.Range(0f, randomFactor));
- if (hasStarted) {
- AudioClip clip = ballSounds[Random.Range(0, ballSounds.Length)];
- audioSource.PlayOneShot(clip);
- rb.velocity += velocityTweak;
- }
- }
- public void Reset() {
- hasStarted = false;
- LockBallToPaddle();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement