• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Mouse 3D Pos (Raycasting or some algorythm?)

Edgamer63

Member
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?
 

TheSnidr

Heavy metal viking dentist
GMC Elder
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! :p

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:
Top