原文地址:https://www.bilibili.com/read/cv16730370?from=note
这里也有视频,同时讲了如何移动角色。
实际是godot帮我们把算法做好了,只需要做好地图边界,填入人物地始点,就会自动算出行动路径。
这里主要使用了Navigation2D,路径规划使用NavigationPolygonInstance。
代码
extends Navigation2D
var start_point = Vector2()
var end_point = Vector2()
var path = []
func _input(event):
// 鼠标获取起止点
if event is InputEventMouseButton and event.pressed:
if event.button_index == BUTTON_LEFT:
print('button pressed left')
start_point = event.position
elif event.button_index == BUTTON_RIGHT:
print('button pressed right')
end_point = event.position
func _process(delta):
// 获取行动路径
path = get_simple_path(start_point,end_point,false)
update()
func _draw():
// 绘制路径:各转换点画圆,路径画线。
for point in path:
draw_circle(point,10,Color(1,1,1))
draw_polyline(path,Color(1,0,0),3,true)
作一些补充
extends Navigation2D
var path = []
var speed = 300
func _ready():
var polygon = NavigationPolygon.new()
var outline = $Polygon2D.polygon # 获取画的多边形的顶点列表
polygon.add_outline(outline) # 把这个多边形数据给控件
polygon.make_polygons_from_outlines() # 创建多边形
$NavigationPolygonInstance.navpoly = polygon # 生成的数据给界面导航组件
set_process(false) # 不需要刷新,结约点资源
func _input(event):
if event is InputEventMouseButton and event.is_pressed() and event.button_index == BUTTON_LEFT:
path = get_simple_path($Icon.position, get_local_mouse_position(),true) # 返回两个给定点之间的路径
$Polygon2D.draw_path_line(path) # 调用控件的画线功能
set_process(true) # 开始刷新
func _process(delta):
var walk_speed = speed * delta # 速度
move_to_path(walk_speed) # 移动到
func move_to_path(walk_speed):
var last_postion = $Icon.position # 角色当前位置
while path.size(): # 有路径值
var distance_between_points = last_postion.distance_to(path[0]) # 角色与路径0之间的距离
if distance_between_points >= 5: # 距离大于5
$Icon.position = last_postion.linear_interpolate(path[0],walk_speed/distance_between_points) # 移动:返回这个向量与 to 之间线性插值的结果
return
last_postion = path[0] # 距离小于5,直接移动到目标位置
path.remove(0) # 移除第0个路径,循环下一路径
set_process(false) # 休息,等待下一次点击
extends Polygon2D
var path = []
func draw_path_line(path):
self.path = path
update()
func _draw():
if path.size()>1:
for i in range(0,path.size()-1,1):
draw_line(path[i],path[i+1],Color(255,0,0))
# update()