0 votes

Hi,
I am trying to draw a polygon with the help of the method drawpolygon method.
The drawpolygon method requires a PoolVector2Array() and PoolColorArray as parameters.
I want to do 3 things:
(a) Draw a rectangle through this method under the virtual function _draw()
(b) Set the colour of the rectangle in consonance with the position of a VSlider node.
(c) Change the colour of the rectangle at runtime by moving the slider position up and down.
I am not sure if I am correctly passing values in the parameters, for I am getting a triangle as opposed to a rectangle. And, neither am I able to get the desired colour nor am I able to change colours by sliding the VSlider at runtime.

Here is my code:

extends Control

onready var slider =$VSlider

func _ready():
    slider.value = 100

func _draw():
    var col = {}
    var points = PoolVector2Array()
    var colour = PoolColorArray()
    points = [Vector2(100,100), Vector2(200,100), Vector2(200,200),Vector2(100,200)]
    colour = [slider.value,1,1,1]
    draw_polygon(points,colour)

Here is the output that I am getting:

Image Link

Please help.

Godot version 3.2.2
in Engine by (100 points)

1 Answer

+2 votes

Almost correct.

  1. Draw is called only once when the node enters the tree. Afterwards, you need to call it via update()
  2. The PoolColorArray requires elements of type Color

This code should work:

extends Control

onready var slider =$VSlider

func _ready():
    slider.value = 1 # must be between 0 and 1
    slider.connect("value_changed", self, "redraw")

func redraw(_value):
    update()

func _draw():
    var points = PoolVector2Array()
    var colour = PoolColorArray()
    points = [Vector2(100,100), Vector2(200,100), Vector2(200,200),Vector2(100,200)]
    colour = [Color(slider.value,1,1,1)]
    draw_polygon(points,colour)
by (1,742 points)

Thank you very much. This works.
I made the slider.value as a fraction of 100 when calling the Color method. The slider was set to 1 to 100 with steps of 1. Therefore, I made it into a fraction of 100.

One question, however:

Why have you put an underscore before value in redraw function? Is that a typical coding style or is it required?

Thanks again.

Line2D attributes
Texture of sprite through drawn polygon

Glad it works! Regarding the underscore: It's used to suppress the editor warning about unused arguments. If you remove it, the code will still work as before, but the editor will show a warning.

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 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 webmaster@godotengine.org with your username.