#arrays #godot
#массивы #godot
Вопрос:
Недопустимый get’index ’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:
Вы получаете ошибку, потому что вы превышаете количество элементов массива.
Чтобы избежать этого, либо увеличьте сетку, либо сделайте так, чтобы игрок не мог покинуть сетку.
Если вы хотите, чтобы игрок мог покинуть сетку, вам, вероятно, придется создать if
условие:
if player_in_grid: grid[new_grid_pos.x][new_grid_pos.y] = ENTITY_TYPES.PLAYER.