compsci-godot-arpg/ch01/lesson-12.org

3.1 KiB

Lesson 12: Player-Enemy Collisions

Notes

add collision shape to enemy sprite

  • add CollisionShape2D to sprite root

add shape

  • select collision shape 2D node from Scene Panel
  • Go to Inspector->CollisionShape2D->Shape
  • select 'CapsuleShape2D' from dropdown

modify shape

  • Inspector->CollisionShape2D->Node2D->Transform
  • Go to Rotation and set to 90 degrees
  • Modify shape via handles to adjust it over sprite

set the z-index

  • in CollisionShape2D to 0
  • in sprite root node to 1

make sure collision shape fits all the animation frames

  • go to the AnimateSprit2D node
  • Inspector->AnimatedSprite2D->Animation->Frame
  • scroll through the frames to see if they fit the collision shape properly

modify the player script to handle the collision

default collision code

  • default collision handling occurs between two CharacterBody2D nodes
  • limits each others movements
  • occurs after the move_and_slide function is called
# Using move_and_collide.
var collision = move_and_collide(velocity * delta)
if collision:
    print("I collided with ", collision.get_collider().name)

handle collisions (scaffolding)

  • first get the number of collisions that occurred

    • this is in get_slide_collision_count() function
  • loop through the number with an index

    • in each loop get the collision info object for that index with get_slide_collisions()

      • get_slide_collision takes an index
    • to get the collider call get_collider() on the collision info object
  • the function scaffolding:
# this is the basic function
func handleCollision():
    for i in get_slide_collision_count():
        var collision = get_slide_collision(i)
        var collider = collision.get_collider()
        priint_debug(collider.name)
  • place this function in func _physics_process(delta)

    • put it after move_and_slide but before updateAnimation
    • example:
func _physics_process(delta):
    handleInput()
    move_and_slide()
    handleCollision()
    updateAnimation()