Ball is passing through instead of Bouncing Back after destroying a brick in a Block Breaker 2D Game (Arkanoid).
I have used Destroy (gameObject) api for destroying and it is not working as per the expectation.
Below is the screenshot of the same.
Please suggest me on this.
Thanks in advance.
Could we have a piece of script of how you handle it?
My wild guess is that the script is atached to the brick and you destoy it before changing the velocity of the ball and therefore the velocity cant be changed.
Hi,
Please find the script below for bricks destruction on collision with the ball.
using UnityEngine;
using System.Collections;
public class Brick : MonoBehaviour {
public int maxHits;
private int timesHit;
private LevelManager levelManager;
// Use this for initialization
void Start () {
levelManager = GameObject.FindObjectOfType();
timesHit = 0;
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D col)
{
timesHit++;
// Destroy(hitInfo.transform.gameObject);
// Destroy(transform.gameobject);
if (timesHit == maxHits)
Destroy(gameObject);
//SimulateWin();
}
void SimulateWin()
{
levelManager.LoadNextLevel();
}
}
Please use Code Tags when posting snippets of code, it makes it much easier to read : Using code tags properly - Unity Engine - Unity Discussions
I’m assuming the problem is that there is a race condition between the collision events. Your ball is likely handling its collision after your brick runs its OnCollisionEnter2D method. So when the ball updates, there is no brick there, and so it just keeps going. This may be happening behind the scenes if you have only applied a physics material to the ball with no script handling the bounce.
One solution is to handle the bounce yourself by reflecting the velocity of the ball in a script on collision.
Another possible solution is hiding the brick for a frame and giving the ball the opportunity to bounce off the collider, then destroying the gameobject. You can do this with a coroutine:
void OnCollisionEnter2D(Collision2D col) {
timesHit++;
if(timesHit == maxHits) {
StartCoroutine(deathCoroutine);
}
}
IEnumerator deathCoroutine() {
yield return new WaitForFixedUpdate();
Destroy(gameObject);
}
If you’re not worried about frame-precision, you can use Destroy(gameObject, 0.1f) which will wait a tenth of a second before killing the brick.
Hey i resolve the issue by changing the velocity of the ball.
1 Like
Sorry to bounce this up, but maybe someone is like me and is looking for the answer to this question! The solution to this problem is very simple:
Click on your Ball object, and go to its RigidBody2D, there is a setting that is named Collision Detection, it’s very likely that yours is on Discreet, change it and put it on Continuous and it should work like a breeze!