<Godot>工厂游戏练习笔记一<2D网格地图>
1、编写网格数据类,用于存储网格地图中的数据:
class_name Grid2D_Data
## 单元格数据,传入一个场景
var data:Resource:
set(val):
if val != null:
data = val
## 网格长宽
var grid_size:Vector2i = Vector2i(10,10):
set(val):
if val:
grid_size = val
## 网格数据
var map_data = []
## 初始化
func _init(p_data:Resource,p_grid_size:Vector2i):
data = p_data
grid_size = p_grid_size
pass
## 创建网格数组
func create(parent:Node2D):
for x in grid_size.x:
var array = []
for y in grid_size.y:
var grid_data = data.instantiate()
grid_data.grid_position = Vector2i(x,y)
grid_data.name = "grid%s_%s" % [x,y]
parent.add_child(grid_data)
array.append(grid_data)
map_data.append(array)
pass
## 获取指定网格坐标数组
func get_cell(pos:Vector2i):
if pos <= grid_size and pos >= Vector2i(0,0):
return map_data[pos.x][pos.y]
else :
return null
pass
## 获取指定列网格
func get_row(x:int):
return map_data[x]
pass
## 打印网格内容
func show():
for x in map_data.size():
print(get_row(x))
pass
## 更改指定网格内容
func set_cell(pos:Vector2i,p_data:Node2D):
if pos <= grid_size and pos >= Vector2i(0,0):
map_data[pos.x][pos.y] = p_data
pass
## 获取网格指定角度数据
func get_cell_direction(pos:Vector2i,degress:int):
if degress == 0:
return get_cell(pos+Vector2i(0,-1))
elif degress == 90:
return get_cell(pos+Vector2i(1,0))
elif degress == 180:
return get_cell(pos+Vector2i(0,1))
elif degress == 270:
return get_cell(pos+Vector2i(-1,0))
else:
return null
pass
2、编写单元格数据类型基类,所有单元格场景需要继承该类
class_name Grid_Data ##网格数据基类
extends Node2D
var grid_position:Vector2i ##网格坐标
var degress:int ##角度
var type:String ##网格类型
var sprite:Sprite2D ##图片
## 修改图片大小
func _set_scale(target:Vector2i):
var sh = sprite.texture.get_height()
var sw = sprite.texture.get_width()
var scale_x = target.x / (sh*1.0)
var scale_y = target.y / (sw*1.0)
self.scale = Vector2(scale_x,scale_y)
pass
3、新建一个地图瓦块场景,用于初始化地图
4、添加脚本,继承基类,初始化地图数据
extends Grid_Data
func _ready():
type = "map"
sprite = $sprite
pass
5、新建一个地图场景map,用于初始化地图,调整图片坐标等
6、在场景map下绑定脚本,初始化地图
extends Node2D
@export var grid_size:Vector2i=Vector2i(10,10): ##网格大小
set(val):
if val:
grid_size = val
@export var cell_size:Vector2i=Vector2i(64,64): ##单元格大小
set(val):
if val:
cell_size = val
var Grid_Map = preload("res://scenes/map/grid_map.tscn")
var map_data:Grid2D_Data ##网格数据实例
func _ready():
map_data = Grid2D_Data.new(Grid_Map,grid_size)
map_data.create(self)
for x in grid_size.x:
for y in grid_size.y:
var grid = map_data.get_cell(Vector2i(x,y))
var sprite = grid.sprite
grid._set_scale(cell_size)
sprite.position = Vector2i((x+0.5)*cell_size.x,(y+0.5)*cell_size.y)
pass
7、后续操作通过点击对应的网格,即可以获取到对应网格绑定的坐标,通过坐标获取上下左右的相对关系。