@itgiawa said:
I'm trying to fire a projectile from my 3D character to my mouse pointer using ray casting.
When I press my input this code is called:
var z = 0
var position2D = get_viewport().get_mouse_position()
var dropPlane = Plane(Vector3(0, 1, 0), z)
var mouse_position3D = dropPlane.intersects_ray($Spatial/Camera.project_ray_origin(position2D),$Spatial/Camera.project_ray_normal(position2D))
var mouse_direction = mouse_position3D.normalized()
spell_instance.look_at(mouse_direction, Vector3.UP)
add_child(spell_instance)
Inside my projectile object I have this:
func _physics_process(delta):
apply_impulse(transform.basis.z, -transform.basis.z)
It kinda works, but it doesnt hit my pointer exactly and I'm not sure why. I don't understand what z is supposed to do. How is it possible to describe a plane in 3D space with a vector and a float? Wouldn't you need two vectors to describe a plane? I cant visualize how the ray casting is supposed to work so its really hard for me to fix...
The Vector is the normal, and then the Z is how far that plane is from origin. For example, if you have a plane defined like Plane(Vector3.UP, 20)
, then the plane will have a normal facing (0, 1, 0)
and will be positioned at (0, 20, 0)
, which is 20 units from the center.
With the pointer, how is it off? Is the height off, or is there an offset on the X or Z axes?
Something you may be able to try is using the project
function to get the mouse position on the plane, using code something like this:
var position2D = get_viewport().get_mouse_position()
var dropPlane = Plane(Vector3.UP, z)
var mouse_depth_distance = 1
var position_in_3D = $Spatial/Camera.project_ray_origin(position2D) + ($Spatial/Camera.project_ray_normal(position2D) * mouse_depth_distance)
var mouse_position3D = dropPlane.project(position_in_3D)
# I think this code may make the instance look at the mouse position a little more reliably, but not totally sure
spell_instance.look_at(spell_instance.global_transform.origin.direction_to(mouse_position3D), Vector3.UP)
add_child(spell_instance)
I have not tested it though, so I'm not sure it will work.