Creating a method to modify collisions for block breaker

I am trying to prevent my ball from getting stuck on the X axis. The goal of my method is to adjust the collision of the ball when it is moving at a speed of slower than 0.5F per second on the X axis so that the ball will not enter a forever loop at 0F. What I have come up with so far is:


   [SerializeField] float SpeedX;

    private void FixMotion()
    {
        Rigidbody2D glitchFix = GetComponent<Rigidbody2D>();

        if (glitchFix.velocity.x <= 0.5f)
        {
            SpeedX = glitchFix.velocity.x + 0.3f;
        }
    }

I am trying to call this method upon my collision event of the ball, but nothing is happening currently. I am calling the method here:


    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (hasStarted)
        {
            AudioClip clip = ballSounds[UnityEngine.Random.Range(0, ballSounds.Length)];
            myAudioSource.PlayOneShot(clip);
        }
        FixMotion();
    }

Could someone explain what I’m doing wrong please? I’m struggling a bit with if else statements and decided to take a small break from the course to work on them so I’m thinking the error may lie somewhere in there. Thanks!

You making your ball going faster. If you need to fix x stuck for ball, try out my method.
! This is paddle script. !
Works fine if ball mass is about 0.25f.
InitialBallSpeed is a float. I dont remember what its value. Need to do tests.

  private void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Ball")
        {
            Rigidbody2D ballRB = coll.gameObject.GetComponent<Rigidbody2D>();
            Vector3 hitPoint = coll.GetContact(0).point;
            Vector3 paddleCenter = new Vector3(this.gameObject.transform.position.x, this.gameObject.transform.position.y);

            ballRB.velocity = Vector3.zero;
            float difference = (paddleCenter.x - hitPoint.x)*initialBallSpeed;

            if (hitPoint.x < paddleCenter.x)
            {

                LeftDir(ballRB, difference);

            }
            else
            {

                RightDir(ballRB, difference);

            }
        }
    }

     void LeftDir(Rigidbody2D ballRB, float difference)
    {
        ballRB.AddForce(new Vector2(-Mathf.Abs(difference), 2f * initialBallSpeed - 0.56f * Mathf.Abs(difference)));
    }

     void RightDir(Rigidbody2D ballRB, float difference)
    {
        ballRB.AddForce(new Vector2(Mathf.Abs(difference), 2f * initialBallSpeed - 0.56f * Mathf.Abs(difference)));
    }
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms