arraysgodotmultiplayerbuildinggodot4

Godot 4 grid base item palcement


i want to make a open multiplayer rpg game with Godot 4. The problem is that, i have seen a video tutorial (here) and i came accross with this error:

Invalid get index '2' (on base: 'Array').

here is my code

extends Node2D

@onready var camp_fire = preload("res://src/Scenes/camp_fire.tscn")
var tile_size =16

enum {OBSTACTLE, COLLECTABLE,RESOURCE}
var grid_size = Vector2(160,160)
var grid = []


func _ready():
    for x in range(grid_size.x):
        grid.append([])
        for y in range(grid_size.y):
            grid[x].append(null)
    var positions = []
    for i in range (50):
        var xcoor = (randi() % int(grid_size.x))
        var ycoor = (randi() % int(grid_size.y))
        var grid_pos = Vector2(xcoor,ycoor)
        if not grid_pos in positions:
            positions.append(grid_pos)

func _input(event):
    if event.is_action_pressed("LeftClick"):
        var mouse_pos = get_global_mouse_position()
        var multiX = int(round(mouse_pos.x)/tile_size)
        var numX = multiX*tile_size
        var multiY = int(round(mouse_pos.y)/tile_size)
            var numY = multiY*tile_size
        var new_pos = Vector2(multiX, multiY)
        var new_camp_fire = camp_fire.instantiate()
        new_camp_fire.set_position(tile_size*new_pos)
        grid[multiX][multiY] = OBSTACTLE
        get_tree().root.get_node("World").get_node("PlayerBuildings").add_child(new_camp_fire)

Solution

  • The solution was simply. I had attach this script at the item which i want player to be able to place. I put this script at Node2D where i spawn the item in map!!!