Hyluss

Pong Ball

Apr 5th, 2019
549
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PongBall : MonoBehaviour
  6. {
  7.     [SerializeField]
  8.     private float speed;
  9.  
  10.     private Vector2 direction;
  11.  
  12.     private float minPositionY;
  13.     private float maxPositionY;
  14.     private float minPositionX;
  15.     private float maxPositionX;
  16.  
  17.     private void Start()
  18.     {
  19.         int randomDirection = Random.Range(0, 2);
  20.         direction = randomDirection == 0 ? Vector2.one.normalized : -Vector2.one.normalized;
  21.     }
  22.  
  23.     private void Update()
  24.     {
  25.         transform.Translate(direction*speed*Time.deltaTime);
  26.  
  27.         if (transform.position.y < minPositionY && direction.y < 0)
  28.         {
  29.             direction.y = -direction.y;
  30.         }
  31.  
  32.         if (transform.position.y  > maxPositionY && direction.y > 0)
  33.         {
  34.             direction.y = -direction.y;
  35.         }
  36.  
  37.         if (transform.position.x < minPositionX && direction.x < 0)
  38.         {
  39.             Debug.Log("Right Win");
  40.             Destroy(gameObject);
  41.         }
  42.  
  43.         if (transform.position.x > maxPositionX && direction.x > 0)
  44.         {
  45.             Debug.Log("Left Win");
  46.             Destroy(gameObject);
  47.         }
  48.  
  49.     }
  50.  
  51.     public void Initialize(SpriteRenderer courtSpriteRenderer)
  52.     {
  53.         SetBallMoveRestriction(courtSpriteRenderer);
  54.     }
  55.  
  56.     public void SetBallMoveRestriction(SpriteRenderer courtSpriteRenderer)
  57.     {
  58.         Sprite ballSprite = GetComponent<SpriteRenderer>().sprite;
  59.  
  60.         minPositionY = courtSpriteRenderer.bounds.min.y + ballSprite.bounds.extents.y * transform.lossyScale.y;
  61.         maxPositionY = courtSpriteRenderer.bounds.max.y - ballSprite.bounds.extents.y * transform.lossyScale.y;
  62.  
  63.         minPositionX = courtSpriteRenderer.bounds.min.x + ballSprite.bounds.extents.x * transform.lossyScale.x;
  64.         maxPositionX = courtSpriteRenderer.bounds.max.x - ballSprite.bounds.extents.x * transform.lossyScale.x;
  65.     }
  66.  
  67.     private void OnTriggerEnter2D(Collider2D other)
  68.     {
  69.         if (other.GetComponent<Paddle>())
  70.         {
  71.             direction.x = -direction.x;
  72.         }
  73.     }
  74. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment