【GDScript】Drag and drop of items
Godot 3.2.4
Then the last article ( [GDScript] Designing Item Properties ) began to do
We started to add drag and drop functions to the items, and started adding the following code to the script of the Goods node
var drag_source # Used to record the last dragged node (exchange data to this node after the item is dropped)
#--------------------------------------------
# Node with methods
#--------------------------------------------
func get_drag_data(position: Vector2):
var drag_node = self.duplicate() # Duplicate the current node for drag and drop display
drag_node.use_top_left = true # Make the picture centered and look natural
drag_node.drag_source = self
set_drag_preview(drag_node) # Set the node dragged by the mouse
return drag_node
func can_drop_data(position: Vector2, data) -> bool:
# Determine if it can be placed on this node
return data && data.get("goods_property") # Only the goods_property property can be put down
func drop_data(position: Vector2, data) -> void:
# Receive dropped node data
swap_goods(self, data.drag_source)
#--------------------------------------------
# custom method
#--------------------------------------------
## Swap two items
## (In fact, the attributes of the two items are made into resources, and the rest of the nodes are the same
## In this way, we only need to exchange the resource attribute to replace the item)
func swap_goods(a, b):
var p_temp = a.goods_property
a.goods_property = b.goods_property
b.goods_property = p_temp
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
I forgot, it was checked in the last tutorial, this time for the Goods nodeuse_top_left
Uncheck it
and then clear itgoods_property
Attribute content, click the small circle arrow on the left to
check the TextureRect nodeExpand
Attributes
Let's create a new scene for the inventory, and add the following nodes
to the GridContainer nodecolumns
property is set to5
Select the GridContainer node, click the link icon above the scene
and searchGoods
Node, and add:
start to design two more items, double-click to select the last oneWeapon_02.tres
Perform the following operations in the file
properties panel to learnAtlasTexture
Use of resources Click TextureRegion
at the bottom of the editor to complete the following:
You can now follow the steps aboveWeapon_03.tres
The properties of the file, I did this. After that
, we drag and drop the finished item resource files one by one to the goods_property attribute of the Goods node in our scene.
Next to witness the moment of miracle, press F6 to run the game:
(End)