How we can conver to prediction line from line to dotted?

godot 4.3

I’m trying to create a prediction line in Godot Engine 4.3. The Line2D ray I drew from point A to point B now appears as a straight line. What do I need to do to turn this ray into a dotted line? The codes I have written so far are as follows:

player.gd :

extends Sprite2D

@export var EXPLOSİON_FORCE : float = 1000.0
const PROJECTILE = preload("res://scenes/rigid_body_2d.tscn")
@onready var TEST_PROJECTİLE: CharacterBody2D = $TestProjectile

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("attack"):
		do_attack()
		
func do_attack():
	var obj := PROJECTILE.instantiate()
	get_tree().root.add_child(obj)
	
	obj.global_position = global_position
	obj.velocity = EXPLOSİON_FORCE * get_forward_direction()

func _process(delta: float) -> void:
	queue_redraw()
	
func _draw() -> void:
	update_trajectory()
	
func get_forward_direction() -> Vector2:
	return global_position.direction_to(get_global_mouse_position())
	
func update_trajectory() -> void:
	var velocity : Vector2 = EXPLOSİON_FORCE * get_forward_direction()
	var line_start := global_position
	var line_end:Vector2
	var gravity:float = ProjectSettings.get_setting("physics/2d/default_gravity")
	var drag:float = ProjectSettings.get_setting("physics/2d/default_linear_damp")
	var timestep := 0.02
	var colors := [Color.DARK_RED, Color.BLUE]
	
	
	for i:int in 70:
		velocity.y += gravity * timestep
		line_end = line_start + (velocity * timestep)
		velocity = velocity * clampf(1.0 - drag * timestep, 0, 1)
		
		var ray := raycast_query2d(line_start, line_end)
		if not ray.is_empty():
			if ray.normal != Vector2.ZERO:
				velocity = velocity.bounce(ray.normal)
				draw_line_global(line_start, ray.position, Color.YELLOW)
				line_start = ray.position
				continue
				
		draw_line_global(line_start, line_end, colors[i%2])
		line_start = line_end
		
func raycast_query2d(pointA:Vector2, pointB:Vector2) -> Dictionary:
	var space_state := get_world_2d().direct_space_state
	var query := PhysicsRayQueryParameters2D.create(pointA, pointB, 1)
	var result := space_state.intersect_ray(query)
	
	if result:
		return result
	else:
		return{}
	
func draw_line_global(pointA:Vector2, pointB:Vector2, color:Color, width:int = 10) -> void:
	var local_offset := pointA - global_position
	var pointB_local := pointB - global_position
	draw_line(local_offset, pointB_local, color, width)

What errors or deficiencies might be in my codes? What is the best approach to create a dotted prediction line?

1 Like

To create a dotted line, I suggest using CanvasItem — Godot Engine (stable) documentation in English instead of draw_line. You’d need to learn a bit on how the draw_multiline function works but I think it will suit your needs. Basically break up the continuous line into multiple segments by creating additional points along the line.

1 Like