Search code examples
c#unity-game-engine

ball is losing velocity when it's supposed to speed up in unity


I'm a beginner to unity, creating a pong style game for practice. The ball is supposed to speed up every time it hits the puck but it loses velocity instead. Any fixes?

using TMPro;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ballscript : MonoBehaviour
{
    public Rigidbody2D rb;
    [SerializeField] private float initialspeed = 10;
    [SerializeField] private float speedinc = 0.25f;
    [SerializeField] private TextMeshProUGUI score;
    private int hitcount;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        hitcount = 0;
        Invoke("StartBall", 2f);  
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        rb.velocity = Vector2.ClampMagnitude(rb.velocity, + (speedinc * hitcount));
        print(rb.velocity); //check velocity

    }
    void StartBall()
    {
        rb.velocity = new Vector2(-1, 0) * (initialspeed + speedinc * hitcount);
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.name == "puck") 
        {
            hitcount += 1;
        }
    }

}

I tried following a tutorial but that didn't help, I also tried to change the values for speedinc and initialspeed


Solution

  • The code in fixed update can not increase the ball's speed because the ClampMagnitude function can only decrease the ball's speed by setting a limit to what it can be. To increase the ball's speed you could scale the ball's velocity inside the OnCollisionExit2D function to speed the ball up as it leaves the puck with code like this:

    void OnCollisionExit2D(Collision2D other)
    {
        if (collision.gameObject.name == "puck") 
        {
            rb.velocity *= (1 + speedinc);
        }
    }    
    

    For scaling the velocity to be guaranteed to work, the velocity after the collision must not be zero. To prevent this from happening you can add a Physics Material 2D and set the Bounciness value to be larger than zero to guaranteed the speed increase to work.