custom_drawing_in_2d.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. .. _doc_custom_drawing_in_2d:
  2. Custom drawing in 2D
  3. ====================
  4. Why?
  5. ----
  6. Godot has nodes to draw sprites, polygons, particles, and all sorts of
  7. stuff. For most cases this is enough, but not always. Before crying in fear,
  8. angst, and rage because a node to draw that specific *something* does not exist...
  9. it would be good to know that it is possible to easily make any 2D node (be it
  10. :ref:`Control <class_Control>` or :ref:`Node2D <class_Node2D>`
  11. based) draw custom commands. It is *really* easy to do it too.
  12. But...
  13. ------
  14. Custom drawing manually in a node is *really* useful. Here are some
  15. examples why:
  16. - Drawing shapes or logic that is not handled by nodes (example: making
  17. a node that draws a circle, an image with trails, a special kind of
  18. animated polygon, etc).
  19. - Visualizations that are not that compatible with nodes: (example: a
  20. tetris board). The tetris example uses a custom draw function to draw
  21. the blocks.
  22. - Managing drawing logic of a large amount of simple objects (in the
  23. hundreds of thousands). Using a thousand nodes is probably not nearly
  24. as efficient as drawing, but a thousand of draw calls are cheap.
  25. Check the "Shower of Bullets" demo as example.
  26. - Making a custom UI control. There are plenty of controls available,
  27. but it's easy to run into the need to make a new, custom one.
  28. OK, how?
  29. --------
  30. Add a script to any :ref:`CanvasItem <class_CanvasItem>`
  31. derived node, like :ref:`Control <class_Control>` or
  32. :ref:`Node2D <class_Node2D>`. Then override the _draw() function.
  33. .. tabs::
  34. .. code-tab:: gdscript GDScript
  35. extends Node2D
  36. func _draw():
  37. # Your draw commands here
  38. pass
  39. .. code-tab:: csharp
  40. public override void _Draw()
  41. {
  42. // Your draw commands here
  43. }
  44. Draw commands are described in the :ref:`CanvasItem <class_CanvasItem>`
  45. class reference. There are plenty of them.
  46. Updating
  47. --------
  48. The _draw() function is only called once, and then the draw commands
  49. are cached and remembered, so further calls are unnecessary.
  50. If re-drawing is required because a state or something else changed,
  51. simply call :ref:`CanvasItem.update() <class_CanvasItem_update>`
  52. in that same node and a new _draw() call will happen.
  53. Here is a little more complex example. A texture variable that will be
  54. redrawn if modified:
  55. .. tabs::
  56. .. code-tab:: gdscript GDScript
  57. extends Node2D
  58. export var texture setget _set_texture
  59. func _set_texture(value):
  60. # if the texture variable is modified externally,
  61. # this callback is called.
  62. texture = value #texture was changed
  63. update() # update the node
  64. func _draw():
  65. draw_texture(texture, Vector2())
  66. .. code-tab:: csharp
  67. public class CustomNode2D : Node2D
  68. {
  69. private Texture _texture;
  70. public Texture Texture
  71. {
  72. get
  73. {
  74. return _texture;
  75. }
  76. set
  77. {
  78. _texture = value;
  79. Update();
  80. }
  81. }
  82. public override void _Draw()
  83. {
  84. DrawTexture(_texture, new Vector2());
  85. }
  86. }
  87. In some cases, it may be desired to draw every frame. For this, just
  88. call update() from the _process() callback, like this:
  89. .. tabs::
  90. .. code-tab:: gdscript GDScript
  91. extends Node2D
  92. func _draw():
  93. # Your draw commands here
  94. pass
  95. func _process(delta):
  96. update()
  97. .. code-tab:: csharp
  98. public class CustomNode2D : Node2D
  99. {
  100. public override _Draw()
  101. {
  102. // Your draw commands here
  103. }
  104. public override _Process(delta)
  105. {
  106. Update();
  107. }
  108. }
  109. An example: drawing circular arcs
  110. ----------------------------------
  111. We will now use the custom drawing functionality of the Godot Engine to draw something that Godot doesn't provide functions for. As an example, Godot provides a draw_circle() function that draws a whole circle. However, what about drawing a portion of a circle? You will have to code a function to perform this, and draw it yourself.
  112. Arc function
  113. ^^^^^^^^^^^^
  114. An arc is defined by its support circle parameters. That is: the center position, and the radius. And the arc itself is then defined by the angle it starts from, and the angle at which it stops. These are the 4 parameters we have to provide to our drawing. We'll also provide the color value so we can draw the arc in different colors if we wish.
  115. Basically, drawing a shape on screen requires it to be decomposed into a certain number of points, linked from one to the following one. As you can imagine, the more points your shape is made of, the smoother it will appear, but the heavier it will be, in terms of processing cost. In general, if your shape is huge (or in 3D, close to the camera), it will require more points to be drawn without it being angular-looking. On the contrary, if your shape is small (or in 3D, far from the camera), you may reduce its number of points to save processing costs. This is called *Level of Detail (LoD)*. In our example, we will simply use a fixed number of points, no matter the radius.
  116. .. tabs::
  117. .. code-tab:: gdscript GDScript
  118. func draw_circle_arc(center, radius, angle_from, angle_to, color):
  119. var nb_points = 32
  120. var points_arc = PoolVector2Array()
  121. for i in range(nb_points+1):
  122. var angle_point = deg2rad(angle_from + i * (angle_to-angle_from) / nb_points - 90)
  123. points_arc.push_back(center + Vector2(cos(angle_point), sin(angle_point)) * radius)
  124. for index_point in range(nb_points):
  125. draw_line(points_arc[index_point], points_arc[index_point + 1], color)
  126. .. code-tab:: csharp
  127. public void DrawCircleArc(Vector2 center, float radius, float angleFrom, float angleTo, Color color)
  128. {
  129. int nbPoints = 32;
  130. var pointsArc = new Vector2[nbPoints];
  131. for (int i = 0; i < nbPoints; ++i)
  132. {
  133. float anglePoint = Mathf.Deg2Rad(angleFrom + i * (angleTo - angleFrom) / nbPoints - 90f);
  134. pointsArc[i] = center + new Vector2(Mathf.Cos(anglePoint), Mathf.Sin(anglePoint)) * radius;
  135. }
  136. for (int i = 0; i < nbPoints - 1; ++i)
  137. DrawLine(pointsArc[i], pointsArc[i + 1], color);
  138. }
  139. Remember the number of points our shape has to be decomposed into? We fixed this number in the nb_points variable to a value of 32. Then, we initialize an empty PoolVector2Array, which is simply an array of Vector2.
  140. The next step consists of computing the actual positions of these 32 points that compose an arc. This is done in the first for-loop: we iterate over the number of points for which we want to compute the positions, plus one to include the last point. We first determine the angle of each point, between the starting and ending angles.
  141. The reason why each angle is reduced by 90° is that we will compute 2D positions out of each angle using trigonometry (you know, cosine and sine stuff...). However, to be simple, cos() and sin() use radians, not degrees. The angle of 0° (0 radian) starts at 3 o'clock, although we want to start counting at 0 o'clock. So we reduce each angle by 90° in order to start counting from 0 o'clock.
  142. The actual position of a point located on a circle at angle 'angle' (in radians) is given by Vector2(cos(angle), sin(angle)). Since cos() and sin() return values between -1 and 1, the position is located on a circle of radius 1. To have this position on our support circle, which has a radius of 'radius', we simply need to multiply the position by 'radius'. Finally, we need to position our support circle at the 'center' position, which is performed by adding it to our Vector2 value. Finally, we insert the point in the PoolVector2Array which was previously defined.
  143. Now, we need to actually draw our points. As you can imagine, we will not simply draw our 32 points: we need to draw everything that is between each of them. We could have computed every point ourselves using the previous method, and drew it one by one. But this is too complicated and inefficient (except if explicitly needed). So, we simply draw lines between each pair of points. Unless the radius of our support circle is big, the length of each line between a pair of points will never be long enough to see them. If this happens, we simply would need to increase the number of points.
  144. Draw the arc on screen
  145. ^^^^^^^^^^^^^^^^^^^^^^
  146. We now have a function that draws stuff on the screen: it is time to call in the _draw() function.
  147. .. tabs::
  148. .. code-tab:: gdscript GDScript
  149. func _draw():
  150. var center = Vector2(200, 200)
  151. var radius = 80
  152. var angle_from = 75
  153. var angle_to = 195
  154. var color = Color(1.0, 0.0, 0.0)
  155. draw_circle_arc(center, radius, angle_from, angle_to, color)
  156. .. code-tab:: csharp
  157. public override void _Draw()
  158. {
  159. var center = new Vector2(200, 200);
  160. float radius = 80;
  161. float angleFrom = 75;
  162. float angleTo = 195;
  163. var color = new Color(1, 0, 0);
  164. DrawCircleArc(center, radius, angleFrom, angleTo, color);
  165. }
  166. Result:
  167. .. image:: img/result_drawarc.png
  168. Arc polygon function
  169. ^^^^^^^^^^^^^^^^^^^^
  170. We can take this a step further and not only write a function that draws the plain portion of the disc defined by the arc, but also its shape. The method is exactly the same as previously, except that we draw a polygon instead of lines:
  171. .. tabs::
  172. .. code-tab:: gdscript GDScript
  173. func draw_circle_arc_poly(center, radius, angle_from, angle_to, color):
  174. var nb_points = 32
  175. var points_arc = PoolVector2Array()
  176. points_arc.push_back(center)
  177. var colors = PoolColorArray([color])
  178. for i in range(nb_points+1):
  179. var angle_point = deg2rad(angle_from + i * (angle_to - angle_from) / nb_points - 90
  180. points_arc.push_back(center + Vector2(cos(angle_point), sin(angle_point)) * radius)
  181. draw_polygon(points_arc, colors)
  182. .. code-tab:: csharp
  183. public void DrawCircleArcPoly(Vector2 center, float radius, float angleFrom, float angleTo, Color color)
  184. {
  185. int nbPoints = 32;
  186. var pointsArc = new Vector2[nbPoints + 1];
  187. pointsArc[0] = center;
  188. var colors = new Color[] { color };
  189. for (int i = 0; i < nbPoints; ++i)
  190. {
  191. float anglePoint = Mathf.Deg2Rad(angleFrom + i * (angleTo - angleFrom) / nbPoints - 90);
  192. pointsArc[i + 1] = center + new Vector2(Mathf.Cos(anglePoint), Mathf.Sin(anglePoint)) * radius;
  193. }
  194. DrawPolygon(pointsArc, colors);
  195. }
  196. .. image:: img/result_drawarc_poly.png
  197. Dynamic custom drawing
  198. ^^^^^^^^^^^^^^^^^^^^^^
  199. Alright, we are now able to draw custom stuff on screen. However, it is static: let's make this shape turn around the center. The solution to do this is simply to change the angle_from and angle_to values over time. For our example, we will simply increment them by 50. This increment value has to remain constant, else the rotation speed will change accordingly.
  200. First, we have to make both angle_from and angle_to variables global at the top of our script. Also note that you can store them in other nodes and access them using get_node().
  201. .. tabs::
  202. .. code-tab:: gdscript GDScript
  203. extends Node2D
  204. var rotation_angle = 50
  205. var angle_from = 75
  206. var angle_to = 195
  207. .. code-tab:: csharp
  208. public class CustomNode2D : Node2D
  209. {
  210. private float _rotationAngle = 50;
  211. private float _angleFrom = 75;
  212. private float _angleTo = 195;
  213. }
  214. We make these values change in the _process(delta) function.
  215. We also increment our angle_from and angle_to values here. However, we must not forget to wrap() the resulting values between 0 and 360°! That is, if the angle is 361°, then it is actually 1°. If you don't wrap these values, the script will work correctly. But angle values will grow bigger and bigger over time, until they reach the maximum integer value Godot can manage (2^31 - 1). When this happens, Godot may crash or produce unexpected behavior. Since Godot doesn't provide a wrap() function, we'll create it here, as it is relatively simple.
  216. Finally, we must not forget to call the update() function, which automatically calls _draw(). This way, you can control when you want to refresh the frame.
  217. .. tabs::
  218. .. code-tab:: gdscript GDScript
  219. func wrap(value, min_val, max_val):
  220. var f1 = value - min_val
  221. var f2 = max_val - min_val
  222. return fmod(f1, f2) + min_val
  223. func _process(delta):
  224. angle_from += rotation_ang
  225. angle_to += rotation_ang
  226. # We only wrap angles if both of them are bigger than 360
  227. if angle_from > 360 and angle_to > 360:
  228. angle_from = wrap(angle_from, 0, 360)
  229. angle_to = wrap(angle_to, 0, 360)
  230. update()
  231. .. code-tab:: csharp
  232. private float Wrap(float value, float minVal, float maxVal)
  233. {
  234. float f1 = value - minVal;
  235. float f2 = maxVal - minVal;
  236. return (f1 % f2) + minVal;
  237. }
  238. public override void _Process(float delta)
  239. {
  240. _angleFrom += _rotationAngle;
  241. _angleTo += _rotationAngle;
  242. // We only wrap angles if both of them are bigger than 360
  243. if (_angleFrom > 360 && _angleTo > 360)
  244. {
  245. _angleFrom = Wrap(_angleFrom, 0, 360);
  246. _angleTo = Wrap(_angleTo, 0, 360);
  247. }
  248. Update();
  249. }
  250. Also, don't forget to modify the _draw() function to make use of these variables:
  251. .. tabs::
  252. .. code-tab:: gdscript GDScript
  253. func _draw():
  254. var center = Vector2(200, 200)
  255. var radius = 80
  256. var color = Color(1.0, 0.0, 0.0)
  257. draw_circle_arc( center, radius, angle_from, angle_to, color )
  258. .. code-tab:: csharp
  259. public override void _Draw()
  260. {
  261. var center = new Vector2(200, 200);
  262. float radius = 80;
  263. var color = new Color(1, 0, 0);
  264. DrawCircleArc(center, radius, _angleFrom, _angleTo, color);
  265. }
  266. Let's run!
  267. It works, but the arc is rotating insanely fast! What's wrong?
  268. The reason is that your GPU is actually displaying the frames as fast as it can. We need to "normalize" the drawing by this speed. To achieve, we have to make use of the 'delta' parameter of the _process() function. 'delta' contains the time elapsed between the two last rendered frames. It is generally small (about 0.0003 seconds, but this depends on your hardware). So, using 'delta' to control your drawing ensures that your program runs at the same speed on everybody's hardware.
  269. In our case, we simply need to multiply our 'rotation_ang' variable by 'delta' in the _process() function. This way, our 2 angles will be increased by a much smaller value, which directly depends on the rendering speed.
  270. .. tabs::
  271. .. code-tab:: gdscript GDScript
  272. func _process(delta):
  273. angle_from += rotation_ang * delta
  274. angle_to += rotation_ang * delta
  275. # we only wrap angles if both of them are bigger than 360
  276. if angle_from > 360 and angle_to > 360:
  277. angle_from = wrap(angle_from, 0, 360)
  278. angle_to = wrap(angle_to, 0, 360)
  279. update()
  280. .. code-tab:: csharp
  281. public override void _Process(float delta)
  282. {
  283. _angleFrom += _rotationAngle * delta;
  284. _angleTo += _rotationAngle * delta;
  285. // We only wrap angles if both of them are bigger than 360
  286. if (_angleFrom > 360 && _angleTo > 360)
  287. {
  288. _angleFrom = Wrap(_angleFrom, 0, 360);
  289. _angleTo = Wrap(_angleTo, 0, 360);
  290. }
  291. Update();
  292. }
  293. Let's run again! This time, the rotation displays fine!
  294. Tools
  295. -----
  296. Drawing your own nodes might also be desired while running them in the
  297. editor, to use as preview or visualization of some feature or
  298. behavior.
  299. Remember to use the "tool" keyword at the top of the script
  300. (check the :ref:`doc_gdscript` reference if you forgot what this does).