# Mouse 3D Pos (Raycasting or some algorythm?)

Discussion in 'Programming' started by Edgamer63, Mar 31, 2019.

1. ### Edgamer63Member

Joined:
Jan 24, 2018
Posts:
66
Hello, i was wondering on how to make a raycast to get the position of the mouse in 3D.... and i have yaw and pitch variables... any idea?

2. ### TheSnidrHeavy metal viking dentistGMC Elder

Joined:
Jun 21, 2016
Posts:
462
This script might help you! It returns the 3D vector of the mouse, as well as the ray's starting position (which, for a perspective projection, is the camera's own position).
Use this to cast a ray onto whatever you'd like to cast rays onto!

One of the simplest shapes to cast rays at is a flat plane at z = 0. The script returns the ray's starting position (o) and its direction (d), and it can then be parametrized as the following:
ray = o + d * t; //where t is a parameter
Now you want to test where the ray's z value equals 0 (ie. where it intersects the plane with z = 0).
ray.z = 0;
This becomes:
o.z + d.z * t = 0;
Now let's solve for t:
t = - o.z / d.z;

And all this in code form:
Code:
```var ray = convert_2d_to_3d(view_camera[0], window_mouse_get_x(), window_mouse_get_y());
var t = - ray[5] / ray[2];
var xIntersect = ray[3] + ray[0] * t;
var yIntersect = ray[4] + ray[1] * t;
var zIntersect = 0;```

Last edited: Mar 31, 2019
Ali Al - Mosawi likes this.