I need a little help. I’ll be glad if anyone can show me the right direction…
My problem is actually quite simple; follow the mouse position on 3D even when camera is rotated.
So I use screen to world calculation. It works great until I start to rotate the camera around and I’m not sure how to handle this situation cause I thought projection matrix is enough to handle and I see it is not(I might be wrong of course)
My screen to world is similar to Rendy’s, except I’m not using frustum.
There is no custom render.script, just rotating the camera using Orbit Camera
Minimal project is here: GitHub - selimanac/look-at-my-mouse
local function screen_to_world(self)
local inv = vmath.inv(self.camera_projection * self.camera_view)
-- Center
local center_x = self.mouse_screen_position.x - ((DISPLAY_WIDTH / 2))
local center_y = self.mouse_screen_position.y - ((DISPLAY_HEIGHT / 2))
-- Near & Far plane
local near_world_position = vmath.vector4(inv * vmath.vector4(center_x, center_y, -1, 1))
local far_world_position = vmath.vector4(inv * vmath.vector4(center_x, center_y, 1, 1))
near_world_position = near_world_position / near_world_position.w
far_world_position = far_world_position / far_world_position.w
local frustum_z = (self.mouse_screen_position.z - self.camera_nearZ) / (self.camera_farZ - self.camera_nearZ)
local world_position = vmath.lerp(frustum_z, near_world_position, far_world_position)
self.mouse_world_position.x = world_position.x
self.mouse_world_position.y = world_position.y
self.mouse_world_position.z = world_position.z
end
function update(self, dt)
-- ROTATE TO MOUSE
if self.mouse_screen_position then
self.camera_projection = go.get(camera_id, "projection")
self.camera_view = go.get(camera_id, "view")
b_screen_to_world(self)
end
if self.mouse_world_position then
self.hero_rotation_angle = math.atan2((self.mouse_world_position.x - self.hero_position.x), (self.mouse_world_position.y - self.hero_position.y)) - math.pi
self.hero_rotation = vmath.quat_rotation_y(-self.hero_rotation_angle)
go.set_rotation(self.hero_rotation, hero_id)
end
end
So, I know this is not a easy task to ask and this is just a hobby project, but I’ll be glad to hear your suggestions.