![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | Bisdante |
Hello there, i have this code that’s supposed to aim and preview the trajectory of a projectile before shooting it using a Line2D and raycasts. It should draw a line that reflects in the walls 5 times, but the reflecting only happens 0-3 times at random angles, and i don’t know why.
here is a link with what is going on at the moment,
And here’s the code.
func get_predicted_path(player):
if Input.is_action_pressed("left"):
rotation_degrees -= 1
if Input.is_action_pressed("right"):
rotation_degrees += 1
var starting_point : Vector2
var end_point : Vector2
var normal : Vector2
var reflect : Vector2
var bounces = 0
points = []
var space_state = get_world_2d().direct_space_state
var result
while bounces < max_bounces: #max_bounces = 5
if starting_point == Vector2.ZERO and end_point == Vector2.ZERO and normal == Vector2.ZERO:
#defines the starting values for the loop
starting_point = global_position
end_point = global_position.direction_to(gun_tip.global_position) * diagonal
points.append(to_local(starting_point))
result = space_state.intersect_ray(starting_point, end_point, [player])
if result.empty(): break
end_point = result.position
normal = result.normal
reflect = (starting_point - end_point).reflect(normal) * diagonal
else:
#now the loop begins "for real"
result = space_state.intersect_ray(end_point, end_point + reflect, [player])
if result.empty(): break
starting_point = end_point
end_point = result.position
normal = result.normal
reflect = (starting_point - end_point).reflect(normal) * diagonal
#adds the calculated point in space to an array
points.append(to_local(starting_point))
bounces += 1
update()
func _draw() -> void:
trajectory.clear_points() #trajectory is a line2D
print(points)
for i in points.size(): #goes through all the calculated points and draws the line
trajectory.add_point(points[i])
When i print the points, it only returns a 2 or 3 element array depending of the angle. I think that for some reason some of the raycasts are not returning the collision against my tilemap, thus, breaking the loop too soon, but i have no idea why this is happening.