How can I make my player/character perform the action of eating an object when I press the spacebar

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

I have a character of a pig as my player, and it is at the end of the level where it must eat a glowing truffles. I have scripted my object with an Area2D with this function
func _on_Truffle_body_entered(body):
queue_free()

However, the orbs disappear when I collide with them, but I have also scripted the pig with the action of eating. I would like my pig to eat the truffles when the spacebar is pressed.

How can I make my pig seem like it is eating the truffles on command, and when the spacebar is pressed?

:bust_in_silhouette: Reply From: ponponyaya

Since your truffle is an Area2D, I think you can try this way.
(In this example, No need signal connect “onTrufflebodyentered”)

[In truffles script]

extends  Area2D

func _input(event):
	if event.is_action_pressed("ui_select"):
		if get_overlapping_bodies().size() > 0:
			queue_free()

P.S. By the way, don’t forget to set “collision layer” and “collision mask” to get correct collision objects.

This helped a lot. Now when the pig is in the vicinity of the truffle it eats it. I was wondering what I had to set my collision layer to, in order to obtain the collision? I want to make it so that the pig collides with the truffle before it eats it.

Juan | 2022-01-09 19:25

Take a look at Godot Doc’s this page: Area2D.

In the method "get overlapping bodies ( ) " it says that “The overlapping body’s CollisionObject2D.collision_layer must be part of this area’s CollisionObject2D.collision_mask in order to be detected.”

So you have to choose a layer, for example Layer 5 and do the following settings.
1.[In truffle Scene] check the Layer 5 of “collision mask”.
2.[In player Scene] check the Layer 5 of “collision layer”.
3.[this step is option] set a name for Layer 5 in “Project Settings”.
P.S. Layer 5 is an example, you can choose any Layer you want.

ponponyaya | 2022-01-10 00:13

:bust_in_silhouette: Reply From: umma

noob here, but try this:

  1. replace the truffles with static body parent, (change the collision layer if you don’t it to collide with the pig)
  2. put the truffle static body in a group (located in inspector) called truffle.
  3. put the area node over the pig, then write
extends spatial

func _process(_delta):
  pass

func on_area_body_entered(body):
  if Input.is_action_pressed("spacebar"):
      if body.is_in_group("truffles")
         $pig_animationplayer.play("truffle_eating")
         body.queue_free()

#just trying to help not an expert