using System.Collections; using System.Collections.Generic; using UnityEngine; public class PongBall : MonoBehaviour { [SerializeField] private float speed; private Vector2 direction; private float minPositionY; private float maxPositionY; private float minPositionX; private float maxPositionX; private void Start() { int randomDirection = Random.Range(0, 2); direction = randomDirection == 0 ? Vector2.one.normalized : -Vector2.one.normalized; } private void Update() { transform.Translate(direction*speed*Time.deltaTime); if (transform.position.y < minPositionY && direction.y < 0) { direction.y = -direction.y; } if (transform.position.y > maxPositionY && direction.y > 0) { direction.y = -direction.y; } if (transform.position.x < minPositionX && direction.x < 0) { Debug.Log("Right Win"); Destroy(gameObject); } if (transform.position.x > maxPositionX && direction.x > 0) { Debug.Log("Left Win"); Destroy(gameObject); } } public void Initialize(SpriteRenderer courtSpriteRenderer) { SetBallMoveRestriction(courtSpriteRenderer); } public void SetBallMoveRestriction(SpriteRenderer courtSpriteRenderer) { Sprite ballSprite = GetComponent().sprite; minPositionY = courtSpriteRenderer.bounds.min.y + ballSprite.bounds.extents.y * transform.lossyScale.y; maxPositionY = courtSpriteRenderer.bounds.max.y - ballSprite.bounds.extents.y * transform.lossyScale.y; minPositionX = courtSpriteRenderer.bounds.min.x + ballSprite.bounds.extents.x * transform.lossyScale.x; maxPositionX = courtSpriteRenderer.bounds.max.x - ballSprite.bounds.extents.x * transform.lossyScale.x; } private void OnTriggerEnter2D(Collider2D other) { if (other.GetComponent()) { direction.x = -direction.x; } } }