Godot - 更改区域内的瓷砖

Godot - Change tiles within an area

我试图做到这一点,如果一个函数被调用,一个被 Collisionshape2D 覆盖的区域会在 TileMap 节点中移除它的图块。我的问题是删除的区域与 Collisionshape2D 不匹配。任何见解表示赞赏!谢谢。

我的代码:

func changeArea(collionshape):
    var corridorTile = $CorridorTiles
    var rect = Rect2(collionshape.position, collionshape.shape.extents*2)
    var topleft = corridorTile.world_to_map(rect.position)
    var bottomright = corridorTile.world_to_map(rect.end)
    for x in range(topleft.x, bottomright.x):
        for y in range(topleft.y, bottomright.y):
            corridorTile.set_cell(x, y, -1)

编辑1*

将代码更改为:

func changeCorridorTile(collionshape):
    var corridorTile = $CorridorTiles
    var extents:Vector2 = collionshape.shape.extents
    var topleft = corridorTile.world_to_map(collionshape.position - extents)
    var bottomright = corridorTile.world_to_map(collionshape.position + extents)
    for x in range(topleft.x, bottomright.x):
        for y in range(topleft.y, bottomright.y):
            corridorTile.set_cell(x, y, -1)
    corridorTile.update_bitmask_region()

collisionShape2D区域覆盖的tileMap单元格被删除。我使用 .bitmask_region() 方法更新它们。

我首先注意到的是,从我的头顶看:Rect2 位置是一个角,但 CollisionShape 位置是中心。

你必须这样做:

var extents:Vector2 = collionshape.shape.extents
var rect := Rect2(collionshape.position - extents, extents * 2)

现在,再看一遍,您根本不需要 Rect2

var extents:Vector2 = collionshape.shape.extents
var topleft = corridorTile.world_to_map(collionshape.position - extents)
var bottomright = corridorTile.world_to_map(collionshape.position + extents)

还有一件事:我相信它在 CollisionShape2D 的父级的本地 space 中(我猜是 Area2D)。因此,如果这不起作用,可能是因为您需要在全局 space 中执行此操作。希望你没有任何旋转(这只会把整个事情搞砸)或缩放,所以这只是使用 global_position.

的问题

附录:我忘记了一些东西,world_to_map 不采用全局坐标。试试这个(假设没有旋转或缩放):

var extents:Vector2 = collionshape.shape.extents
var position := corridorTile.to_local(collionshape.global_position)
var topleft = corridorTile.world_to_map(position - extents)
var bottomright = corridorTile.world_to_map(position  + extents)