custom_drawing_in_2d.rst 16 KB

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