- Home /
[Solved] Find the position ALONG a raycast
The title sums up my question. How do I find a point along a raycast. I don't mean the start or the end or even where it collides with an object. Say if the distance from the one object to another was 10. How can I find out what the position is halfway between those objects using a raycast. Thanks in advanced!
Answer by Hoeloe · Nov 08, 2014 at 11:45 PM
Basic maths is how you do it. What is a ray? It's a line starting from a defined point, travelling in one direction. If you define your ray with start and end points, then this direction vector is just (end-start), which you then normalise to make it direction only.
To find the point at any distance, d, along a ray is very simple. Take the start point, S and the direction vector V, and the point you're looking for is just:
S + Vd
As long as the direction vector is normalised (has magnitude 1). This is very basic vector maths, and if you're doing anything at all with raycasts, I really strongly suggest you read into it more. You should have a thorough understanding of vector maths whatever you do. You'll need it.
Hmm. So I put this down RaycastHit hit; if(Physics.Raycast(transform.position, (player.position - transform.position), out hit, 100)) { cube.transform.position = (transform.position + ((player.position - transform.position) * hit.distance/2)); Debug.DrawRay(transform.position,(player.position - transform.position),Color.cyan); }
where player is the target (I am raycasting between this object and the player, and successfully. the Debug.DrawRay proves that) and cube should be the center of the raycast. Ins$$anonymous$$d the cube is projected in the opposite direction as the raycast. Have I done something wrong?
Use the 101/010 button to format code. Sounds like an unintentional inversion, where you've subtracted A-B ins$$anonymous$$d of B-A, or a necessary inversion is missing, where you'd write -myVector
So I realized what my problem was, first off my direction was not normalized and second my distance was hit.distance/2. This was updating every frame so even after I normalized the direction I the position was sporadically changing. Here is my final script. Thanks guys for helping me out!
Vector3 direction = player.position - transform.position;
RaycastHit hit;
if(Physics.Raycast(transform.position, (direction), out hit, 100))
{
cube.transform.position = (transform.position + (direction.normalized*distance)));
Debug.DrawRay(transform.position,(direction),Color.cyan);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613171042im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Firing a RayCast in a Raycast, Rayception 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
AI Pathfinding using RayCast 0 Answers
using A* pathfinding to go to player after raycast has seen it - c# 0 Answers