Why "func _draw()" function not work when I click the icon?

Godot 4.2.1

I have godot 4.2.1 project and I want to create prediction line when I click the ball, here is my code:

extends Node2D

var is_shooting = false
var shooting_angle = 0.0
var shooting_power = 0.0
var start_point = Vector2.ZERO
var end_point = Vector2.ZERO

var ball : Sprite2D = Sprite2D.new()

func _ready():
	ball.texture = preload("res://ball.png")
	ball.position = Vector2(get_viewport_rect().size.x / 2, get_viewport_rect().size.y)
	ball.scale = Vector2(0.1, 0.1)

func _input(event):
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				is_shooting = true
				shooting_angle = calculate_shooting_angle()
				shooting_power = calculate_shooting_power()
				start_point = $ball.global_position
				end_point = calculate_end_point()
				is_shooting = false

	elif event is InputEventMouseMotion and is_shooting:
		shooting_angle = calculate_shooting_angle()
		shooting_power = calculate_shooting_power()
		end_point = calculate_end_point()

func _draw():
	if is_shooting:
		print("show me draw in console")
		draw_line(start_point, end_point, Color(1, 0, 0))

func calculate_shooting_angle():
	return $ball.global_position.angle_to_point(get_global_mouse_position())

func calculate_shooting_power():
	return get_global_mouse_position().distance_to($ball.global_position) * 0.1

func calculate_end_point():
	var t = shooting_power / 9.8
	var x = start_point.x + shooting_power * cos(shooting_angle) * t
	var y = start_point.y + shooting_power * sin(shooting_angle) * t + 0.5 * 9.8 * t * t
	return Vector2(x, y)

but when I click the ball, this function not work “func _draw():”, even I did not know what is the reason, any idea?

_draw() call once, you will need update _draw()


The _draw() function is only called once, and then the draw commands are cached and remembered, so further calls are unnecessary.
If re-drawing is required because a state or something else changed, simply call CanvasItem.update() in that same node and a new _draw() call will happen.

1 Like

That’s for Godot 2.1

In Godot 4.x the function is CanvasItem.queue_redraw()


tnx it is work now, actually to get out of the question, I want to click the ball and create prediciton line but it is not work like that, when ı click the mouse left, my code create line according to mouse, do you have any idea to update my code?

ops, thanks for correction :+1:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.