Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Scorpio |
So, I’m trying to make my character to look at the cursor like a top-down shooter game, but in 3D. Any ideas?
Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Scorpio |
So, I’m trying to make my character to look at the cursor like a top-down shooter game, but in 3D. Any ideas?
Reply From: | Joel_127 |
You need to do a raycast of your mouse position in the 3D world.
var camera = $Camera
var from = camera.project_ray_origin(event.position)
var to = from + camera.project_ray_normal(event.position) * ray_length
The variable “to” will give you the point in 3D where to look (use function “look_at”).
Hey! thanks for the idea!
so, I tried to put the code in the Camera node’s script
and it says "Attempt to call function ‘project_ray_origin’ in base ‘null_instance’ on a null instance.
what does it mean?
Scorpio | 2019-04-06 09:14
this error is because the object on which you call project_ray_origin is null. If the script is on your camera, you should just call “project_ray_origin(event.position)”
Joel_127 | 2019-04-09 14:49
Reply From: | R3tr0 |
hey, i’ve just follow this tutorial to see what i can do, (am working on a top down game), so i’ve used this tutorial: https://www.youtube.com/watch?v=mmvIkkKJVlQ
and this is my code, it works for me:
#gettign the current phyisics state
var space_state = get_world().direct_space_state
#getting the current mouse position
var mouse_position = get_viewport().get_mouse_position()
rayOrigin = camera.project_ray_origin(mouse_position)
rayEnd = rayOrigin + camera.project_ray_normal(mouse_position) * 2000
var intersection = space_state.intersect_ray(rayOrigin, rayEnd)
if not intersection.empty():
var pos = intersection.position
mesh.look_at(Vector3(pos.x, 0, pos.z), Vector3(0,1,0))
mesh.rotate_y(deg2rad(180))
the camera is a reference to your camera
and the rayOrigin and the rayEnd are both empty Vector3
(i used 0 instead of pos.y because i dont want the player to look up and down, if you do change this part to pos.y)