Several CollisionShape2D for a AnimatedSpriteFrame

Viewed 158

I want to use CollisionPolygon2D for AnimatedSprite to attach to each frame perfectly but I can't do it. Is there a way to define a unique CollisionPolygon2D for each frame? Thanks.

2 Answers

The AnimatedSprite node is only concerned with graphics. And you would need the CollisionPolygon2D as children of a physics object (e.g. KinematicBody2D). Thus, you need something else to orquestarte them.

You may, for example, have multiple CollisionPolygon2D, one per AnimatedSprite frame. Have them all disabled, and in the _process of the physics object, you can enable only the one for the current frame:

var prior_frame:int = 0

func _process(_delta:float) -> void:
    var sprite:AnimatedSprite = $AnimatedSprite

    # make sure the collision for the current frame is not disabled
    var curr_collision := get_node(str("Coll", sprite.frame)) as CollisionPolygon2D
    curr_collision.disabled = false

    # if the frame is the same we last seen, we are done
    if prior_frame == sprite.frame:
        return
    
    # the frame is different, thus disable the collision for the prior frame
    var old_collision := get_node(str("Coll", prior_frame)) as CollisionPolygon2D
    old_collision.disabled = true

    # keep track of the frame we have seen
    prior_frame = sprite.frame

The above code assume that you have nodes called Coll0, Coll1, Coll2 and so on. One per frame of the AnimatedSprite.

Use an AnimationPlayer node. You can then set any parameter of your CollisionShape.

To do this:

  • Select the AnimationPlayer node.
  • Select the CollisionShape node.
  • In the inspector tab you can now see a little key next to the properties.
  • Select shape to see the collision shape.
  • Now click the key next to shape and the name of the property.
  • In your animation in the AnimationPlayer node, there is little diamond around the timeline.
  • Move around the animation and change the properties to the desired values.
Related