Compute world coordinates from mouse coordinates

Hi guys,

I recently tried to compute world space coordinates from mouse coordinates. I looked at the related logic node code (MouseCoordsNode.hx, ScreenToWorldSpaceNode.hx), but they seem to be off and it seems to me they’re missing a prescaling of the mouse coords. It took me quite some time to come up with a working solution, so I post it here in case someone else needs this.

EDIT New and cleaner approach:

var camera = cast(object, CameraObject);
var mouse = Input.getMouse();
var v = RayCaster.getRay(mouse.x, mouse.y, camera).at(0);

Previous approach:

import iron.system.Input;
import iron.object.CameraObject;
import iron.math.Vec4;
import iron.math.Mat4;

import kha.System;

var camera = cast(object, CameraObject); // assumes you're calling this from a Trait on your camera

var v = new Vec4();
var m = Mat4.identity();

var w = System.windowWidth();
var h = System.windowHeight();

var mouse = Input.getMouse();
var mx = 2 * ((mouse.x / w) - 0.5);
var my = -2 * ((mouse.y / h) - 0.5);

v.set(mx, my, 0, 1);
m.getInverse(camera.VP);
v.applyproj(m);

// world space coordinates are now in v
2 Likes

Nice! That’s the code i wanted