0 votes

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


        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

        #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

    bounces += 1

func _draw() -> void:
trajectory.clear_points() #trajectory is a line2D
for i in points.size(): #goes through all the calculated points and draws the line

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.

Godot version 3.2.3.stable.mono.official
in Engine by (32 points)

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.