Picking up an item

Godot V4.2

Can anyone Eli5, because that’s how old i feel right now, why this isn’t working?

I have a characterbody2D (my player) and a rigidbody2d (a spear), that I would like the player to pick up and throw whenever they feel like it. So far I have been able to have them meet in game and I know they can interact with each other due to some print statements I have, but I cant actually pick the spear an add it to my character.

I have 4 scenes. My level, my player, the floor and the spear (which is in a group named spear and the area2d on the spear is in a group spear_area).
The only script I have is on my character. Which has the basic movement godot gives, my detection area2d, and my pick input. My code should be in bold.

extends CharacterBody2D

var able_to_pick = false

const SPEED = 300.0
const JUMP_VELOCITY = -400.0

var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)

func _on_detection_area_entered(area):
if area.is_in_group(“spear_area”):
able_to_pick = true

func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta

if Input.is_action_just_pressed(“pick”) and able_to_pick == true:
var spear = get_tree().get_nodes_in_group(“spear”)
spear.position = $Marker2D

# Handle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
	velocity.y = JUMP_VELOCITY

# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("left", "right")
if direction:
	velocity.x = direction * SPEED
	velocity.x = move_toward(velocity.x, 0, SPEED)


It appears “spear” is actually an array since that’s what get_nodes_in_group returns. Try getting the first node in the group with get_first_node_in_group.

1 Like

Thank you for helping me with not reading correctly. “nodes” def would mean me getting array. Now I have to solve my invalid set index position.

Which line is the invalid set index on?

spear.position = $Marker2D

Marker2D is a node, not a position (Vector2). You need to do $Marker2D.position.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.