Search code examples
godotgdscript

How to change collisionPolygon shape using set_deferred?


I'm trying to change my CollisionPolygon2D shape via code as such:

...

self.polygon[0].x+=100

but it gives the error:

area_set_shape_disabled: Can't change this state while flushing queries. Use call_deferred() or set_deferred() to change monitoring state instead.

which is why I'm assuming I'll need to use set_deferred() to change the shape
so how do I achieve this?


Solution

  • It may be useful to use this pattern:

    1. Get a copy of the value
    2. Modify the temporary value
    3. Set the value back
    var temp_polygon = get_polygon()
    temp_polygon[0].x -= 100
    call_deferred("set_polygon", temp_polygon)
    

    call_deferred is a function that calls functions by name. Here the name was "set_polygon" and the second argument is the argument for set_polygon. It calls the function later in order to avoid conflicts like this. I would prefer call_deferred over set_deferred because the setter function is less likely to cause problems as well.

    As a final note, try to avoid directly accessing properties, and use the setter and getter functions when possible.