Hyluss icon

Pong Ball

Hyluss | PRO | 04/05/19 12:42:43 PM UTC | 0 ⭐ | 472 👁️ | Never ⏰ | []
C# |

2.11 KB

|

None

|

0 👍

/

0 👎

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<SpriteRenderer>().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<Paddle>())
        {
            direction.x = -direction.x;
        }
    }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎