So I’m making a simple pong/breakout style game, and am really struggling with this issue re. ball physics. It’s better seen than explained, so here’s a 20 second video showing my issue:
(I have logged the ball’s velocity each frame, so you can track it in the console)
In words: ball starts off with ideal velocity of (2f, 10f), but eventually, as it collides with the boxes moving by, it speeds up more and more with each collision, or ocassionally slows down significantly.
Goal: keep ball velocity constant before and after collisions.
Here’s what the inspector for the blocks looks like (rigidbody 2D is kinematic):
Here’s what the inspector for the ball looks like (rigidbody2D is dynamic, gravity = 0):
Ball script:
[SerializeField] paddleStandardRed paddle1;
[SerializeField] float xVelocity = 2f;
[SerializeField] float yVelocity = 10f;
float xVel, yVel;
private bool hasStarted;
Vector2 paddleToBallVector;
Vector2 velocityDesired;
// Start is called before the first frame update
void Start()
{
paddleToBallVector = transform.position - paddle1.transform.position;
velocityDesired = new Vector2(xVelocity, yVelocity);
xVel = Mathf.Abs(xVelocity);
yVel = Mathf.Abs(yVelocity);
}
// Update is called once per frame
void FixedUpdate()
{
if(hasStarted == false)
{
LockBallToPaddle();
}
Debug.Log(GetComponent<Rigidbody2D>().velocity);
/*
if(hasStarted == true)
{
float clampXVel = Mathf.Clamp(GetComponent<Rigidbody2D>().velocity.x, -xVel, xVel);
float clampYVel = Mathf.Clamp(GetComponent<Rigidbody2D>().velocity.y, -yVel, yVel);
GetComponent<Rigidbody2D>().velocity = new Vector2(clampXVel, clampYVel);
}
*/
LaunchOnKeyDown();
}
private void LaunchOnKeyDown()
{
if(Input.GetKeyDown(KeyCode.Space))
{
hasStarted = true;
GetComponent<Rigidbody2D>().velocity += new Vector2(xVelocity, yVelocity);
}
}
void LockBallToPaddle()
{
Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
transform.position = paddlePos + paddleToBallVector;
}
Any help would be appreciated!