- Home /
RayCast issue (Beginner) - My Raycasts seem to randomly miss their targets.
Hi,
Before a block of my game is destroyed, I want it to check (with a Raycast) the block above it and tell that other block it's "collapsing". To do so, I've made the method below:
private BlockCollapse collapse;
public void BlockDestroy(GameObject blockToDestroy)
{
RaycastHit hit;
Ray ray = new Ray(blockToDestroy.transform.position, blockToDestroy.transform.position + Vector3.up);
if (Physics.Raycast(ray, out hit, 1))
{
if (hit.collider.tag == "Block")
{
GameObject target = hit.collider.gameObject;
collapse = target.GetComponentInChildren<BlockCollapse>();
collapse.collapsing = true;
}
}
Destroy (blockToDestroy);
}
Issue is that the Raycast misses the block above it every once in a while! (The block is destroyed, but the boolean "collapsing" of the block above isn't set to "true".)
I've tried to call this method from multiple places (OnTriggerEnter(), Update(), FixedUpdate()), but the result is always the same: The Raycast misses its target at seemingly random times...
Any suggestion to make my raycasts 100% reliable?
Thanks!
Answer by robertbu · Jan 31, 2014 at 09:51 PM
Your problem is on line 6. For the direction portion of the ray construction, you don't want to add the position. Instead:
Ray ray = new Ray(blockToDestroy.transform.position, Vector3.up);
Note you could avoid the ray and use an alternate form of Raycast() instead:
if (Physics.Raycast(blockToDestory.transform.position, Vector3.up, out hit, 1))