Flavio Silva
Flavio Silva

Reputation: 123

Detect collision between two 2D kinematics bodies godot

I'm doing a very simple 2D platform game project, you can see here how it is so far: https://master.d3kjckivyd1c76.amplifyapp.com/src/Games/PlatformGame2D101/index.html

But I can't detect the collision between the enemy (the chainsaw) and the player.

I have this code to detect if the two bodies are colliding, but it only prints the Enemy when the player is moving:

func _physics_process(delta: float) -> void:
  velocity = move_and_slide(velocity, Vector2.UP)

  for i in get_slide_count():
    var collision = get_slide_collision(i)
    if collision.collider.is_in_group("Enemy"): print("Enemy")

Thanks any help : )

Upvotes: 0

Views: 582

Answers (2)

Flavio Silva
Flavio Silva

Reputation: 123

The answer: https://www.reddit.com/r/godot/comments/yojmz8/detect_collision_between_two_2d_kinematics_bodies/

But basically the player, it’s not moving, so it's not colliding 🤦

Here it's the changes that I made to fix: https://bitbucket.org/201flaviosilva-labs/platform-game-2d-101-godot/commits/61e37823eb9758fdafd222f2cdecf3e0668a3808

Upvotes: 0

Kristian Perriu
Kristian Perriu

Reputation: 1

I did plenty of 2d games using pygame and i used this two.

  1. You can use sprite.spritecollideany() which takes 2 arguments. The sprite u want to collide, in your case the chainsaw with another group of sprites. this requires a loop, which will look like this:

     for swordman in swordsmen1_army:
     # Swordsman1 attackin Swordsman2
     colliding_sword2 = pygame.sprite.spritecollideany(swordman, swordsmen2_army)
     if colliding_sword2:
         swordman.attacking = True
         swordman.unleash = False
         if swordman.index == 3:
             colliding_sword2.health -= SWORD_HIT
    
  2. If you want to collide just two sprites you can use pygame.Rect.colliderect() which checks for detection of 2 sprites with each other. This one requires no loop and looks like this:

     if pygame.Rect.colliderect(ball.rect, border1.rect):
     ball.down_collision = True
     ball_y_speed *= -1
    

Both of them will return a boolean value and from there, you can use an if statement and continue with the code.

Upvotes: 0

Related Questions