Raycast3d cast_to lenght with code

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

Hi there, im making my enemies detect the player with raycast on enemy instances. cast to lenght is set to “-15” Z axis.
but i wanna set this value with a script so that i can give it a random lenght between two numbers. i write the random number part, but dunno how to set cast lenght with code.

:bust_in_silhouette: Reply From: jgodfrey

Assuming you already have the correct vector, you should only have to:

  • Normalize it (set its length to 1)
  • Multiply it by your random length value
  • Store that in the Raycast.cast_to property

So, something like this, I think…

$Raycast.cast_to = $Raycast.cast_to.normalized() * random_length_value

If you ask vector of the raycast, i have not. Cause i add raycast as a node.
Should i create the raycast with the script aswell?

Var space = Get_world() .direct_space_state
Var raycast_v = Space.intersect_ray(transform.origin, vector3(0,0,-15)

İ think raycast_v Will have My raycast vector with this. And Also whenn i use the line of code that you write, it Will work. I also need delete the raycast node i suppose.
Well im not at home right now, i Will try this tomorrow.

morningkingdom | 2020-11-04 18:51

Sorry, I’ve corrected a few things in my above response (though, not tested).

Depending on the details, you should be able to add the Raycast as as a node and reference it similar to the above…

jgodfrey | 2020-11-04 19:04

thank you, its work smootly.

and if someone need it, this is the code, also include randomize part for length value:

onready var player_detect_ray_cast = get_node("RayCast")

var random_ray_cast_lenght_value = RandomNumberGenerator.new()

func _process(delta):


func _ready():
	var ray_cast_length_value = random_ray_cast_lenght_value.randf_range(10,30)
	player_detect_ray_cast.cast_to = player_detect_ray_cast.cast_to.normalized() * ray_cast_length_value

and i did not delete the raycast that i add as a node…

thank you again for your time.

morningkingdom | 2020-11-05 17:29