Need to have different outcomes based on the collider using get_collider()

Godot Version

v4.2.2.stable.official [15073afe3]


I am making pong. My ball is a CharacterBody2D scene. My player and cpu paddles are StaticBody2D scenes. I have instantiated them all into my game scene. In the game scene I have a node called TopBotBorder which is a StaticBody2D as well that has two CollisionShape2D children to act as the top and bottom borders.

Within my ball script I have referenced my player and cpu scenes as follows.

@onready var Player = get_tree().get_first_node_in_group("player")
@onready var CPU = get_tree().get_first_node_in_group("cpu")

Then in my _physics_process(delta) function I have tried to make a variable called collision (to handle the move_and_collide), a variable called collider (to denote what object collided with the ball), and an if statement to try and handle the case of if I hit the player, the cpu, or the TopBotBorder. As noted below.

func _physics_process(delta):
	var collision = move_and_collide(ballDirection*speed*delta)
	var collider
	if collision:
		collider = collision.get_collider().name
		# if ball hits player or cpu paddle
		if collider == or
			speed += ballAccel
                #if ball hits TopBotBorder

In my output it is printing TopBotBorder when it hits a TopBotBorder, Player when it hits the player paddle, and CPU when it hits the cpu paddle. I can’t seem to get it to be selective for just the player or cpu paddle in that if statement.

Thanks for your time. Also, this is my first ever post so if I’ve done some formatting or etiquette error please provide feedback.

Thats happen because your if statment is wrong, you do two checks and if one of them evalutes to true the code inside the if block will be called. The first check you check if collider is equal to player name, that’s correct, if the player name is equal to collider will execute the if block, but the problem is the other check, you’re not checking if collider is equal to, you’re checking if the variable evalutes to true and any non-empty string evalutes to true in an if check that’s the problem, so this line should be: if collider == or collider ==

I think the problem is the lack of parentheses here:

if collider == or

“==” takes priority over “or”. This means your code is equivalent to:

if (collider == or (

And so it’s printing the name whenever is truth-y. Which is all the time.
But what you probably actually want is this:

if (collider == or (collider ==
1 Like

Thanks for the reply! This for sure helped me understand if statements a lot better and I appreciate your time and response. I have been digging around for like 4 hours in the gdscript documents seeing if i was misunderstanding something and finally thought I’d ask.

1 Like

Thank you! This has greatly increased my understanding of how if statements check things!