How can I pick up and drop items?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jujumumu

When I mine a block in my game I want a item to appear in the world and when the player walks over the item it gets picked up and disappears. I want the items to be affected by gravity so they will fall until they hit a collisiondetection2d. A system similar to terraria’s system. How could I accomplish that?

:bust_in_silhouette: Reply From: johnygames

In order for items to be affected by gravity, they need to either have custom logic implemented or be RigidBodies. Save yourself the trouble and create Rigidbodies.

Now, if I understand this correctly, you need some sort of falling crates or packages that the player can collect. You can create RigidBodies and detect collision with the player by using signals. I guess your player character has an Area2D which is capable of detecting collisions with other Area nodes and RigidBody nodes. So, here’s how to do this:

  1. Go to your player’s Area2D node and create a new script.

  2. Then create anbody_entered() signal (from the panel on the right, under Node tab)

  3. A new func _on_Area2D_body_entered(body) function will appear in the Area node’s script

  4. Write the following code in order to have the collectible destroy itself everytime it touches the Area2D node:

func _on_Area2D_body_entered(body):
	if body.name=='<object's name>':
		body.queue_free()

You can also create a variable which changes whenever a collectible is picked.

Does that answer your question? If it does, please upvote this answer and mark it as best.

Perfect answer just what I was looking for.

jujumumu | 2019-08-06 17:42

A good answer but I want the items to collide with the world but not with each other how could I do that?

jujumumu | 2019-08-06 20:26

You do that with collision masks and layers. You place objects that you want to collide with each other in the same collision layer. Objects not belonging in the same layer do not collide. Check the docs for a better definition of collision mask and collision layer:
Physics introduction — Godot Engine (3.1) documentation in English

So, as an experiment, try this:

  1. Go to your collectible (RigidBody node) and open the Collision tab under PhysicsBody2D
  2. Uncheck collision layer/mask 1 and check collision layer/mask 2
  3. Supposing the other nodes are on collision layer 1, your collectible will ignore collisions with them

Also check this out:
https://forum.godotengine.org/4010/whats-difference-between-collision-layers-collision-masks

johnygames | 2019-08-06 21:12