I am building a Pong game. and the player has the ability to catch the ball with the paddle by holding down the space bar. The paddles move up and down on the y axes by using the up and down arrows. After the player releases the space bar I would like to figure if the paddle is traveling up or down and “throw” the ball in the direction of travel of the paddle. I’m having a hard time being able to record the paddles Y position between updates because the function for throwing seems to happen a lot faster than the frame rate.
Here is my code for the ball and how I’m trying to throw it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallController : MonoBehaviour {
private PaddleController _paddle;
private bool hasStarted = false;
private Vector3 paddleLastKnownPosition;
// Use this for initialization
void Start () {
InvokeRepeating("StartBall", 2f, 1f);
}
// Update is called once per frame
void Update () {
if (_paddle)
{
HoldToPaddle();
paddleLastKnownPosition = _paddle.transform.position;
}
}
private void HoldToPaddle()
{
Vector3 ballPos = new Vector3(transform.position.x, transform.position.y);
ballPos.y = _paddle.transform.position.y;
transform.position = ballPos;
}
void StartBall()
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-15f, 5f);
CancelInvoke("StartBall");
}
void OnCollisionEnter2D(Collision2D collision)
{
Vector2 tweak = new Vector2(Random.Range(0f, 0.1f), Random.Range(0f, 0.1f));
if (hasStarted)
{
GetComponent<AudioSource>().Play();
GetComponent<Rigidbody2D>().velocity += tweak;
}
}
//let's the ball know that it's caught when the space bar is held down and it colides with the paddle
public void Caught(PaddleController paddle)
{
_paddle = paddle;
GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
HoldToPaddle();
}
//throw ball when space bar is let go
public void Throw()
{
float xVelocity = -15f;
float yVelocity = 5f;
if (_paddle.transform.position.x < 0f)
{
xVelocity = -xVelocity;
}
print(paddleLastKnownPosition.y + " : " + _paddle.transform.position.y);
if (_paddle.transform.position.y > paddleLastKnownPosition.y)
{
yVelocity = -yVelocity;
}
else if (_paddle.transform.position.y < 0f)
{
yVelocity = -yVelocity;
}
GetComponent<Rigidbody2D>().velocity = new Vector2(xVelocity, yVelocity);
_paddle = null;
}
}