- Home /
block a raycast from passing through objects
I have build a scene with multiple objects which change materials when clicked on them. Please download the sample scene I have made.
http://www.mediafire.com/download/6tfz4yc7fldyo2m/3DroomTest.exe
the problem is, the raycast goes through objects and affects objects behind them.
here is the script I use
var hit : RaycastHit;
var matArray : Material[];
private var index : int;
function Update () {
if (Input.GetMouseButtonDown(0) && collider.Raycast( Camera.main.ScreenPointToRay(Input.mousePosition), hit, Mathf.Infinity)) {
index++;
index = index % matArray.Length;
renderer.material = matArray[index];
}
}
Just for check, the see-through object have colliers on them?
yes, they have physical box collides. download and test the scene and you will know what exactly is the problem.
Answer by aldonaletto · Nov 10, 2013 at 10:21 AM
That's because you're using collider.Raycast, which ignores other colliders, and the script is attached to the clickable objects: you click on an object, but the script running in another object behind him also "thinks" to have been clicked. A simple solution is to use OnMouseDown instead:
var matArray : Material[];
private var index : int;
function OnMouseDown(){
index++;
index = index % matArray.Length;
renderer.material = matArray[index];
}
NOTE: This code requires mouse, thus it won't work in touch-only devices. A more general case must use Physics.Raycast and make sure that only the object clicked increments the material:
var matArray : Material[];
private var index : int;
function Update(){
var hit : RaycastHit;
if (Input.GetMouseButtonDown(0)
&& Physics.Raycast( Camera.main.ScreenPointToRay(Input.mousePosition), hit)
&& collider == hit.collider){ // only this object responds to the click
index++;
index = index % matArray.Length;
renderer.material = matArray[index];
}
}
Answer by meat5000 · Nov 10, 2013 at 10:07 AM
Use Physics.Raycast not Collider.Raycast
Collider Raycast ->
Description
Casts a Ray that ignores all Colliders except this one.
Physics.Raycast will stop at the first collider it hits.
I thought about this same solution at first, but found a flaw: all clickable objects switch materials whenever any object is clicked.
Answer by Avengerxp · Nov 11, 2013 at 03:31 AM
Thank you all, will test this and update! Works perfect!! I used the Physics.Raycast variant ... Thank you
Your answer
Follow this Question
Related Questions
Changing material Color using RBG? 3 Answers
Using Three sliders (RGB) to change the sea color 1 Answer
Make changes to Sprites/Default Material and not saving this change in prefabs. 1 Answer
ExecuteInEditMode doesn't work on instantiated list of objects? 1 Answer
HDRP has no Emission effect,HDRP Setting emission has no effect 0 Answers