Ball ignoring collision

Hi, ive completed the course now, in hope of this bug im having would be fixed, but it hasn’t.
https://youtu.be/Thcb2cQpo8Q ive recorded it and put it up on youtube, for people to see.
Basicly the ball is going like its supposed to, but every now and then the ball will ignore collisions with either the blocks or the paddle. All of my code is like in the course. Ive changed the sizes of the blocks to accomodate more blocks on the screen, to about 50% size of the regular size. i can put up my code if its needed, i’ve put up the Ball.cs. because i think the problem is within that script. My own guess is that the Random.Range in the velocity might be the culprit. But im not sure why it gives me this bug.

Summary

`public class Ball : MonoBehaviour
{
//configuration parameters
[SerializeField] Paddle paddle1;
[SerializeField] float xPush = 2f;
[SerializeField] float yPush = 15f;
[SerializeField] AudioClip ballSounds;
[SerializeField] float randomFactor = 0.2f;

//state
Vector2 paddleToBallVector;
bool hasStarted = false;

//cached component references
AudioSource myAudioSource;
Rigidbody2D myRigidBody2D;

// Start is called before the first frame update
void Start()
{
    paddleToBallVector = transform.position - paddle1.transform.position;
    myAudioSource = GetComponent<AudioSource>();
    myRigidBody2D = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update() {

    if (!hasStarted) {
        LockBallToPaddle();
        LaunchOnMouseClick();
    }
}

private void LaunchOnMouseClick() {
    if (Input.GetMouseButtonDown(0)) {
        hasStarted = true;
        myRigidBody2D.velocity = new Vector2(xPush, yPush);
    }
}

private void LockBallToPaddle() {
    Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
    transform.position = paddlePos + paddleToBallVector;
}

private void OnCollisionEnter2D(Collision2D collision) {
    Vector2 velocityTweak = new Vector2 //Break line of code, for easier readability for the user, but it doesnt break the functionality
        (Random.Range(0f, randomFactor), 
        Random.Range(0f, randomFactor)); 

    if (hasStarted) {
        AudioClip clip = ballSounds[UnityEngine.Random.Range(0, ballSounds.Length)];
        myAudioSource.PlayOneShot(clip);
        myRigidBody2D.velocity += velocityTweak;
    }
    
}

}`

Try setting the balls collider to continous.

1 Like

Love the amazing help and support in here <3
Thank you very much, it solved the problem ! :smiley: ill read into the difference later today to get better understanding ! but thank you so much !
-Henrik

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

Privacy & Terms