Raycast collision act unpredictable

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lamp.milan

I currently working on a top-down shooter game. But the shoot collision detection doesn’t really work. When I aim at an enemy directly most of the time it doesn’t respond, sometimes doesn’t even aim directly at the enemy, but it responds, and sometimes it just works fine.


var aimRay_origin = Vector3()
var aimRay_target = Vector3()

onready var aimcast = $player/AimCast
onready var aimtarget = $aimTarget

	
func _physics_process(delta):
	
	
	var mouse_position = get_viewport().get_mouse_position()

	ray_origin = $Camera.project_ray_origin(mouse_position)
	ray_target = ray_origin + $Camera.project_ray_normal(mouse_position) * 2000
	
	var intersection_cursor = space_state.intersect_ray(ray_origin, ray_target)
	
	if not intersection.empty():
		aimtarget.global_transform.origin = intersection_cursor.position * 1000
		
	$player/AimCast.cast_to = aimtarget.global_transform.origin
:bust_in_silhouette: Reply From: DaddyMonster

I quickly put together a test project and there were quite a few undeclared variables / mismatched naming / unreferenced variables in your code. I’m assuming aimTarget is a spatial - not sure why you need this but I’ve kept it in case there’s a use I don’t know about.

This works fine for me:

extends Spatial

var ray_origin = Vector3()
var ray_target = Vector3()

onready var aimcast = $Player/AimCast
onready var aimtarget = $aimTarget


func _physics_process(delta):
	var space_state = get_world().direct_space_state
	var mouse_position = get_viewport().get_mouse_position()
	ray_origin = $Camera.project_ray_origin(mouse_position)
	ray_target = ray_origin + $Camera.project_ray_normal(mouse_position) * 2000
	var intersection = space_state.intersect_ray(ray_origin, ray_target)
	if not intersection.empty():
		aimtarget.global_transform.origin = intersection.position * 1000
		$Player/AimCast.cast_to = aimtarget.global_transform.origin

Hope that helps