Code just not working properly

Godot version 4.2.1

Hello everyone,
So I am new to Godot and am following a tutorial to get me started -( Godot Game Development – Crash Course for Beginners by freeCodeCamp.org on Youtube)- I have followed
the tutorial exactly up to the point around 59:48 and at that point he runs the code. When he does this he enters the frogs detection radius from the right and it prints right, and when he enters from the left it prints left, It doesn’t do that or work for me and only prints right. I have re-written the code multiple times and followed the tutorial frame by frame making sure I did everything the same, There is no difference in the code at all but it doesn’t work and I am just stumped. if there are any wizards on here who can magic up a solution I would be incredibly grateful. Any and all help appreciated and sorry for the long paragraph. All code is the same as in the video up until 59:48.

My code for the frog at that point in video. Only prints right, tried printing direction and that always stays above 0 as well for some reason.

extends CharacterBody2D

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

func _physics_process(delta):
#Frog gravity.
velocity.y += gravity * delta

move_and_slide()

func _on_player_detection_body_entered(body):
if body.name == “Player”:
var player = get_node(“…/…/Player/Player”)
var direction = (player.position - self.position).normalized()
if direction > 0:

		print("right")
	else:
		print("left")

I think this line should be if direction.x > 0: ?

1 Like

Your code isn’t identical to the video. You need to use the x component of direction to check if something is on the left or the right side.

if direction.x > 0.0:

Also in the video player variable was declared outside of the function. If you need to store a reference to the player, there’s no need for the get_node() function:

func _on_player_detection_body_collision(body):
    if body.name == "Player":
        player = body

One potential cause for your problem is, that the Player and Frog are children of different Node2Ds. If the positions of those Player and Mobs nodes are different, the comparison won’t work properly. You can fix it by making sure they are both positioned at (0, 0) or by using global_position instead of position.

var direction = (player.global_position - global_position).normalized()

or

var direction = player.global_position.direction_to(global_position)
2 Likes

Thanks for the reply, that was an error over here it is direction.x in the actual code, my bad.

Thanks A lot! I will give these things a try and let you know if it works. (Update: It works! thanks for the tip on variables and the global position worked great. You are officially the post wizard and I appreciate the help a ton! Making games is so cool :slight_smile:

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