- Home /
How to Raycast from Camera View Point?
Hey all, I looked at a bunch of questions but nothing seemed to answer my question. How do I Raycast towards something I'm looking at? Also, how would I place a cube at the place where the raycast hits? My code right now is:
RaycastHit hit;
void Update () {
if (Input.GetButtonDown("Fire1")){
bool doesCollide = Physics.Raycast(transform.position, transform.forward *10, out hit, 10);
if(doesCollide){
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = hit.transform.position + hit.normal;
}
}
}
But this tends to give weird results with cubes being places behind or in weird places. Also this script is attached to an object which is a attached my main camera (I don't know if that is the right terminology). Thanks in advance for your help.
Answer by Bunny83 · Mar 09, 2012 at 12:58 AM
@rutter is right, at least almost ;)
With hit.transform
you access the object you've hit. .position
will just return the pivot point of that object. That's not what you need. Take a look at the RaycastHit struct. It has a member called .point
which hold the actual hit position in world space coordinates.
Answer by rutter · Mar 09, 2012 at 12:39 AM
On this line:
cube.transform.position = hit.transform.position + hit.normal;
I'm not sure why you're adding the collision normal? More importantly, the base position of the object that was hit isn't necessarily quite the same as the point of impact. You probably want to use hit.point
instead.
You asked about raycasting from the camera. If you want to cast a ray through a specific point on the screen, you could use Camera.ScreenPointToRay(). I haven't tried casting a ray through a specific object in the scene, but looking at this I imagine you might be able to use something like so:
var origin = Camera.main.transform.position; var ray = new Ray( origin, transform.position - origin );
He's adding the hit normal to move the cube a bit out of the surface he has hit. The pivot of the cube is in the center so if you place the cube at the hit point, the cube will be stuck half way in.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Bottom area of a 3D model? Raycast? 1 Answer
How to get the distance between two objects in feet/meter? 1 Answer