- Home /
RaycastHit and Camera through walls
Hello!
I've been trying to make my camera not move through walls with RaycastHit, but I really can't get it to work. This is what I've come up with so far.
void Update ()
{
RaycastHit wallHit = new RaycastHit ();
Ray wallRay = new Ray (car.transform.position, camera.transform.position);
if (Physics.Raycast (wallRay, out wallHit, distance)) {
if (wallHit.collider.tag == "Wall") {
camera.transform.position = wallHit.point;
}
}
}
Can you spot what I am doing wrong? Any help is massively appreciated!
Answer by Eno-Khaon · Apr 14, 2015 at 08:58 PM
The direction of your ray is way off.
Think of it this way: Your car is at (50, 10000, 20), so your camera is at, say, (50, 10005, 25). Your ray is shooting from (50, 10000, 20) and going to (100, 20005, 45).
Your ray needs to be:
Ray wallRay = new Ray (car.transform.position, camera.transform.position - car.transform.position);
Thank you, that makes sense. It still doesn't work though. :(
The only other not-as-clear thing I see right now is the "distance" variable, which I assume is simply a maximum distance the camera will be from the car? If (camera.transform.position - car.transform.position).magnitude is greater than "distance" your check may not work correctly.
As an alternative, with tags, it's always integral to double- and triple-check capitalization. As a third party, I can't ensure that "Wall" is spelled with a capital "W" for your tag and that every wall has that tag on it.
public float distance = 6.4f;
transform.position = car.position;
transform.position -= currentRotation * Vector3.forward * distance;
Part of the problem is that you are using the car's position as the ray origin
Ray wallRay = new Ray (car.transform.position, camera.transform.position - car.transform.position);
Use the camera's position as the ray origin
Ray wallRay = new Ray (camera.transform.position, car.transform.position - camera.transform.position);
Right now it might be hitting the wrong side of the cube
However the whole script you provided seems wrong. If you want the Camera to not move if there is a block in the way, why are you moving the camera only if the ray hits an obstacle?
That almost fixed it!
When I slowly reverse my car into a wall, it doesn't go through it, but when I get closer the camera starts to "crawl" down the wall. Any way to NOT make that happen? :)
Thanks a lot to both of you for your help so far!
Your answer
![](https://koobas.hobune.stream/wayback/20220613193133im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Zoom Camera when it hits a wall (edited) 1 Answer
RE: RaycastHit and camera through walls 0 Answers
Raycast hitting objects to the left of my player 1 Answer
Detecting when camera's near clip plane is hit 2 Answers
camera detecting walls 1 Answer