# Setting a point with a ray C#

I have finally figured what a ray is and how to make one in C#. The whole reason why I made the ray, however, was to be able to set my mouse location as a point in a 3D enviroment.

So… how would I use my ray to set a point

Before you get made at me for not looking on the scripting reference, I am able to say in my defense that i found something that possibly could be what I’m looking for. Unfortunately it didn’t come with an explanation of what it was.

``````	print(ray.GetPoint(10));
``````

Here is my first script that has the ray following my mouse pointer.

``````using UnityEngine;
using System.Collections;

public class Raycast : MonoBehaviour
{

void Update ()
{ Ray ray = camera.ScreenPointToRay(new Vector3( Input.mousePosition.x, Input.mousePosition.y , Input.mousePosition.z));
Debug.DrawRay(ray.origin, ray.direction * 100, Color.red);
}
}
``````

Imagine you are standing at a window looking out at your yard and some mountains in the distance. Image you put finger on the glass a bit to the right of you at eye level and sight along the tip of your finger. If what you sight is close to the window, it might be only a few feet to the right. But if your finger landed on the mountains in the distance, the position your finger indicates might be miles to your right. That is, where an object is in 3D space is highly dependent on the distance that object is from the viewing plane.

Ray.GetPoint() gets a point the specified distance from the origin along the ray. It can work to translate a mouse position into a world position. The one thing to note is that Camera.ScreenPointToRay() returns a a ray that starts at the camera near clipping plane, not at the camera. So if you do:

`````` Vector3 pos = ray.GetPoint(10);
``````

You are finding a point a bit further than 10 units from the camera.

An alternate method of doing what you are attempting here is to Camera.ScreenToWorldPoint(). The ‘z’ of the Vector3 you pass to this function is the distance in front of the camera you want to use to generate the point.

A bit of a nit, but you don’t need create a new Vector3 from the mousePosition. Input.mousePosition is already a Vector3. So you can do:

``````Ray ray = camera.ScreenPointToRay(Input.mousePosition);
``````