Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class BallVelocity2 : MonoBehaviour
- {
- public Collider2D PaddleCollider;
- private Rigidbody2D m_BallRigidbody2D;
- private Collider2D m_BallCollider;
- [Tooltip("Set the intial velocity")]
- public Vector2 Velocity = new Vector2(1.1f,1.0f);
- [Tooltip("Percent increment per TimeIncrement. i.e. 2.5 = 2.5%")]
- [Range(0f, 10f)]
- public float Increment = 2.5f;
- [Tooltip("Time each increment is applid")]
- [Range(0f, 20f)]
- public float TimeIncrement = 3f;
- // Store these for use each fixed update
- private Vector3 m_NewVelocityLeft, m_NewVelocityRight;
- // Store if we have rebounded this collision
- private bool m_Rebounding = false;
- void Awake()
- {
- // Set references to require components
- m_BallRigidbody2D = GetComponent<Rigidbody2D>();
- m_BallCollider = GetComponent<Collider2D>();
- m_NewVelocityRight = new Vector2(Velocity.x, Velocity.y);
- m_NewVelocityLeft = new Vector2(-Velocity.x, Velocity.y);
- m_BallRigidbody2D.velocity = new Vector2(Velocity.x, -Velocity.y);
- StartCoroutine(IncrementVelocity());
- }
- private void FixedUpdate()
- {
- // Manually check we have collided with paddle or are about to
- if (m_BallCollider.IsTouching(PaddleCollider))
- {
- // Check we are not currently rebounding (still touching collider after last)
- if (!m_Rebounding)
- {
- m_Rebounding = true;
- float dist = transform.position.x - PaddleCollider.transform.position.x;
- if (dist > 0)
- {
- print("right");
- // Set velocity once only in fixed update
- // This is so other standard collisions will work, i.e. walls
- m_BallRigidbody2D.velocity = m_NewVelocityRight;
- }
- else
- {
- print("left");
- m_BallRigidbody2D.velocity = m_NewVelocityLeft;
- }
- }
- }
- else
- {
- // If not touching then we're clear of rebounding
- m_Rebounding = false;
- }
- }
- public IEnumerator IncrementVelocity()
- {
- yield return new WaitForSeconds(1);
- m_NewVelocityLeft += m_NewVelocityLeft * (Increment/100);
- m_NewVelocityRight += m_NewVelocityRight * (Increment / 100);
- StartCoroutine(IncrementVelocity());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement