I want to understand Ray class in Unity 3D. I have referred the Unity documentation for the same. To create a ray we need to position of origin and direction. The document describes it as:
Using this definition I want to create a ray originating from an object (say a cube) to another object (say sphere). This second object's position basically determines direction of the ray. So I have created a script which asks for the two game objects. The script is:
I have attached above script to an empty game object. When I play the game, I don't find a line between the two objects.
I found that direction of ray is not along position of Sphere but somewhere else. After investigating I found that point of direction is considered as World's origin (0, 0, 0).
Could anyone please let me know what the exact issue is? Why I'm not getting a ray between the two objects?
The second argument of Ray() is a direction and not a position. Directions are vectors that you can think of as like the points on a compass, north, east, south, west. Although positions and directions are both vectors, it's usually a mistake to think they are the same animal. (For example, directions often work best when they are normalised, that is, has a length of one.)
In your case, if you travel from the cube to the world origin, and then travel to the sphere, you've travelled from the cube to the sphere. Put another way, the vector that is the result of subtracting the position of the cube from the position of the sphere is the direction of the sphere from the cube.
answered Sep 13 '11 at 02:23 PM
Graham Dunnett ♦♦
You technically don't need to use a ray in order to draw a line between two positions in the game, you could simply do:
And your debug would work.
In order to get the ray working, you need to do a few things:
To get the end point, you need to add the direction vector, scaled (multiplied) by the distance or the origin.
If this is slightly confusing for you, I would suggest reading up on Vector Math, as it might help. Here's a decent place to start: http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/
answered Sep 13 '11 at 02:30 PM
Thanks to both of you Graham and Zapdot for providing correct information. Graham provided me a conceptual information which is reminder of my early vector basics where Zapdot provided me working code that I was wanted know to visualize a ray. Thanks to both of you!!!
answered Sep 13 '11 at 04:56 PM