- Home /
Raycast doesn't update
Hello! Let me explain the scenario first.. I have a character which places a bomb at the same spot he is currently. After 2.6sec bomb should explode and destroy what's in its way, that should be the box when character is out of way.
The problem is that it always kills the character too, although I set 2.5 sec delay, and if the last updated hit returns box, shouldn't it destroy only a box?
I tried using coroutines to time Raycast and Destroy just before bomb disappears, but nothing happens when bomb disappears...
Here's the destroy part of the code:
void FixedUpdate () {
RaycastHit2D hit = Physics2D.Raycast (bomb.transform.position, Vector2.up, 2);
Debug.Log (hit);
Destroy (hit.collider.gameObject,2.5f);
}
Answer by Baste · Oct 09, 2014 at 01:45 PM
The raycast happens instantly, and records the first object it hits. When you set 2.5f delay on the Destroy, that delays the Destroy, not what gets destroyed.
What happens in your code now is that every fixed update, which is quite often - the bomb checks what's directly above it, and sets that object to be destroyed in 2.5 seconds.
Assuming you place the bomb by using Instantiate, you get the behavior you want by using a Coroutine, like this:
void Start() {
StartCoroutine(DoDestroy());
}
IEnumerator DoDestroy() {
yield return new WaitForSeconds(2.5f);
RaycastHit2D hit = Physics2D.Raycast (bomb.transform.position, Vector2.up, 2);
Debug.Log (hit);
Destroy (hit.collider.gameObject,2.5f);
}
Note that the bomb still only destroys stuff that's directly above it. If you want to destroy everything around it, you need to use Physics2D.OverlapCircleAll.
Hello @Baste! Thanks for your help.. I've tried what you recommended, it seems that the raycast recognizes does execute after 2.5sec delay, but now It won't destroy the box..
Here's the code, I've been trying to figure this out myself for 16 hours now but I just can't get it to work.. I've added the coroutine to PlaceBomb script because when it was in it own script I don't know how to target Bomba(Clone) in other script..
Also thanks for the Physics2d.OverlapCircleAll, I wanted to do achieve similar effect with 4 raycasts in the first place but I'll do it with that class now :)
Thanks again!