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:
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.
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 );
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.