- Home /
How can i make the ray cast don't go through the walls
So basically i want to know what shell i add to this code so the raycast wont go through the GameObjects here's the code.
var Range : float;
function Update () {
var forward = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
Debug.DrawRay(transform.position , forward * Range , Color.blue);
if (Input.GetMouseButtonDown(0)){
if (Physics.Raycast(transform.position , forward , hit , Range)){
Debug.Log("hit");
if (hit.collider.gameObject.name == "Cube1"){
Destroy(gameObject.Find("Cube1"));
Debug.Log("heyeyyey");
}
}
}
}
Answer by robertbu · Jul 13, 2013 at 03:41 AM
Raycast() stops a the first collider it finds. You need multiple layers and layer masks to get Raycasts to ignore an object. Given that you are not using a mask in your Raycast(), the problem is elsewhere. I see two possibilities.
One line 17, you use gameObject.Find("Cube1"). This will find a game object with that name, but, unless there is exactly one object with that name in the scene, it will not necessarily find the game object hit by the collider. You can change your code to:
Destroy(hit.collider.gameObject);
The other possibility concerns how your walls are constructed. If you made them out of planes and used a shader with culling turned off, then you will have a problem. Planes are one-sided, so they will only report a hit from one side. If this is the problem you can change the collider on your walls to a Box colliders.
i made a test walls made of cubes i didn't use planes , i used cube1 just for a test of my code it's my first time using raycast i don't know alot about it.
So you only have one cube with the name 'Cube1'? And somehow your raycast is finding object behind walls? Put this in Update() to verify where your raycast is pointing:
Debug.DrawRay(transform.position, transform.forward * Range);
Note you can use 'transform.forward' ins$$anonymous$$d of your TransformDirection() calculation.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Help with Enemy AI 1 Answer
Accessing colliders, in if statement 2 Answers
How do I make a respawn system? 1 Answer
Sphere cast thing help please!!!! 1 Answer