1
\$\begingroup\$

I am new to game development, I am practicing by creating a pong game.

I currently have an Area2D set up with a signal listening for body_exited (the body in question being the ball), it detects the ball exiting and then resets the ball in the middle of the screen. However, it only does this once. If the ball leaves the Area2D again, it doesn't fire and reset.

Pong field

Screenshot of scene hierarchy

extends Node2D

func _on_area_2d_body_exited(body):
    $Ball.StaticBody2D.position = Vector2(550, 325)
\$\endgroup\$
1
  • \$\begingroup\$ I don't know if this would help, but you could try sending the detected body to the position, so if the ball leaves, it would send it back. So what I mean is do this: body.position = Vector2(550,325) I don't know if this is a smarter solution (You could also use groups so you only move the ball). \$\endgroup\$ Nov 24, 2023 at 7:13

1 Answer 1

3
\$\begingroup\$

The ball being an static body is odd... I suspect the Area2D is not detecting the static body at all, see the issue: Area2D does not detect moving StaticBody2D.

I would like to encourage to change the ball to be either a CharacterBody2D (KinematicBody2D in Godot 3.x) or a RigidBody2D. Your code should be easier to adapt to CharacterBody2D/KinematicBody2D as you can continue to move it by the same means.

The RigidBody2D might save you the code for the ball bouncing (you might want to remove gravity), but you need trickery to teleport it...

Teleporting a RigidBody2D:

PhysicsServer2D.body_set_state(
    rigid_body_2d.get_rid(),
    PhysicsServer2D.BODY_STATE_TRANSFORM,
    Transform2D.IDENTITY.translated(Vector2(1.0, 2.0))
)

Note: If you are using Godot 3, you would use Physics2DServer instead of PhysicsServer2D.


Consider also using areas around the playing field, either using big RectangleShape2D or WorldBoundaryShape2D (which is intended for this use case).


For advice on which physics body to use consider: When should I use a KinematicBody or a RigidBody for 2D platformer characters?

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .