Godot 3.1无效的get'index'16'(基于base:Array)

时间:2019-04-09 22:25:58

标签: arrays godot

无效的“索引'16”(基于数组)。

嗨,我在播放器尝试移至 数组大小(平铺大小)。 错误发生在第54行:

grid[new_grid_pos.x][new_grid_pos.y] = ENTITY_TYPES.PLAYER

我坚持如何解决它。 问候 杰森

extends TileMap

var tile_size = get_cell_size()
var half_tile_size = tile_size / 2

enum ENTITY_TYPES {PLAYER, OBSTACLE, COLLECTIBLE}

var grid_size = Vector2(16,16)
var grid = []

onready var Obstacle = preload("res://scenes/Obstacle.tscn")
func _ready():
    # Creates grid array of grid_size
    for x in range(grid_size.x):
        grid.append([])
        for y in range(grid_size.y):
            grid[x].append(null)
    print(ENTITY_TYPES)
    # Create obstacle positions array
    var positions = []
    # create 5 obstacles
    for n in range(5):
        # random positions constrained to grid_size
        var grid_pos = Vector2(randi() % int(grid_size.x),randi() % int(grid_size.y))
        #check random posisitions not already in array before adding new one
        if not grid_pos in positions:
            positions.append(grid_pos)
    for pos in positions:
        var new_obstacle = Obstacle.instance()
        new_obstacle.position = (map_to_world(pos) + half_tile_size)
        grid[pos.x][pos.y] = ENTITY_TYPES.OBSTACLE
        add_child(new_obstacle)

func is_cell_vacant(pos, direction):
    # Return true if cell is vaccant, else false
    var grid_pos = world_to_map(pos) + direction

    # world Boundaries
    if grid.pos.x < grid_size.x and grid_pos.x >= 0:
        if grid.pos.y < grid_size.y and grid_pos.y >= 0:
            #return true if grid[grid_pos.x][grid_pos.y] == null else false
            return grid[grid_pos.x][grid_pos.y] == null
    return false


func update_child_pos(child_node):
    # Move a child to a new position in the grid array

    # Returns the new target world position of the child
    var grid_pos = world_to_map(child_node.position)
    grid[grid_pos.x][grid_pos.y] = null

    var new_grid_pos = grid_pos + child_node.direction
    grid[new_grid_pos.x][new_grid_pos.y] = ENTITY_TYPES.PLAYER

    var target_pos = (map_to_world(new_grid_pos) + half_tile_size)
    return target_pos
    pass

1 个答案:

答案 0 :(得分:0)

由于超出数组元素,因此收到错误消息。

为避免这种情况,请增大网格或使其变大,以使玩家无法离开网格。

如果您希望玩家能够离开网格,那么您可能必须创建一个if条件:

if player_in_grid: grid[new_grid_pos.x][new_grid_pos.y] = ENTITY_TYPES.PLAYER.