how do i make a character in 3d move to where i click? like in dota or league. so far all I've gotten is making right click an input. I'm assuming there's a built in function to get click position but I can't find it in the documentation. The floor is flat so I'd assume I only need the x,z coords of the click but im really confused a. ty
Here’s a script attached to the Player node, it’s the only script in the scene. It checks for the mouse click, shoots a ray to find the mouse click position within the 3D world, then moves the player towards the selected position.
extends CharacterBody3D
const RAY_LENGTH: float = 1000.0
const THRESHOLD: float = 0.5
const SPEED: float = 5.0
@export var selector: Node3D
var is_clicked: bool
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("click"):
is_clicked = true
func _physics_process(delta):
select_position()
move_to_selection()
func select_position() -> void:
if not is_clicked:
return
var space_state = get_world_3d().direct_space_state
var cam = get_viewport().get_camera_3d()
var mousepos = get_viewport().get_mouse_position()
var origin = cam.project_ray_origin(mousepos)
var end = origin + cam.project_ray_normal(mousepos) * RAY_LENGTH
var query = PhysicsRayQueryParameters3D.create(origin, end)
var result = space_state.intersect_ray(query)
if result:
selector.global_position = result.position
is_clicked = false
func move_to_selection() -> void:
if global_position.distance_to(selector.global_position) < THRESHOLD:
velocity = Vector3.ZERO
return
var direction: Vector3 = selector.global_position - self.global_position
velocity = direction.normalized() * SPEED
move_and_slide()
You need to additionally setup a “click” InputAction in the Project Settings for this to work.