0 votes

Hey there! So I'm currently experimenting with GDScript and Godot alike and I've run into a bit of a wall that I can't figure out how to resolve.

So I'm basically trying to make a scene for a tree that when a player walks into it's Area2D node, a popup will display saying "this tree can be cut down". Now at first I thought "well I'll just check to see if a kinematicbody2D enters the tree's Area2D that should work, but then I realized that this would cause some issues if I add other nodes/scenes later down the line that are also kinematicbody2D (I only want it to recognize the player).

So here is what I have so far:
Player's script:

extends KinematicBody2D

class_name Player

var uid = self.get_instance_id()

Tree's script:

extends Area2D

class_name ChopOakTree

var uid = self.get_instance_id()
var player = Player.new()

func _on_Choppable_Oak_Tree_body_entered(body: KinematicBody2D):
    print("Oak Tree: ", uid)
    print("Entered Body ", body.get_instance_id())
    print("Player ", player.uid)
    if(body.get_instance_id() == player.uid):
        print("Works")`

Now I thought that would work, but for some reason the entered body (even though it is definitely the player) and the player instance id's do not match:

Oak Tree: 1301
Entered Body 1306
Player 1302

Hopefully someone could point me in the right direction towards success with this task, thanks in advance :)

in Engine by (25 points)

Thank you, I appreciate it :)

2 Answers

+1 vote
Best answer

Since you have class_name Player just use if body is Player: as your conditional.

by (3,389 points)
selected by

Yep, this worked for me, I'm going to toy around with it some more to see if I can get it to work when there are multiple instances of Player in the scene.

Thanks for the help!

+1 vote

Better you can try

func _on_Choppable_Oak_Tree_body_entered(body):
    if body.name =="Player":
        print("this body was player")
by (884 points)

I thought about this too, but eventually, I want to add multiplayer functionality to my game so I don't want this function to trigger for all player instances, just the exact player instance that entered the area2d.

It will work there too...
Just you need to rename other players according to there net id

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.