参考
YouTube:https://youtu.be/HmnwNadwHWI
kidscancode:基于网格的运动
extends KinematicBody2D
var grid_size = 16
var inputs ={
'ui_up':Vector2.UP,
'ui down'Vector2.DOWN,
'ui left':Vector2.LEFT,
'ui_right':Vector2.RIGHT
}
func _unhandled_input(event):
for dir in inputs.keys():
if event.is_action_pressed(dir):
move(dir)
func move(dir):
position += inputs[dir] * grid_size
extends KinematicBody2D
onready var ray = $RayCast2D
var grid_size = 16
var inputs ={
'ui_up':Vector2.UP,
'ui down'Vector2.DOWN,
'ui left':Vector2.LEFT,
'ui_right':Vector2.RIGHT
}
func _unhandled_input(event):
for dir in inputs.keys():
if event.is_action_pressed(dir):
move(dir)
func move(dir):
var vector_pos = inputs[dir] * grid_size
ray.cast_to = vector_pos
ray.force_raycast_update()
if !ray.is_colliding():
position += vector_pos
为盒子也添加一个RayCast2D。
extends KinematicBody2D
onready var ray = $RayCast2D
var grid_size = 16
var inputs ={
'ui_up':Vector2.UP,
'ui down'Vector2.DOWN,
'ui left':Vector2.LEFT,
'ui_right':Vector2.RIGHT
}
func move(dir):
var vector_pos = inputs[dir] * grid_size
ray.cast_to = vector_pos
ray.force_raycast_update()
if !ray.is_colliding():
position += vector_pos
return true
return false
将box添加到“box”组。
继续修改Player的代码如下:
extends KinematicBody2D
onready var ray = $RayCast2D
var grid_size = 16
var inputs ={
'ui_up':Vector2.UP,
'ui down'Vector2.DOWN,
'ui left':Vector2.LEFT,
'ui_right':Vector2.RIGHT
}
func _unhandled_input(event):
for dir in inputs.keys():
if event.is_action_pressed(dir):
move(dir)
func move(dir):
var vector_pos = inputs[dir] * grid_size
ray.cast_to = vector_pos
ray.force_raycast_update()
if !ray.is_colliding():
position += vector_pos
else:
var collider = ray.get_collider()
if collider.is_in_group("box")
if collider.move(dir):
position += vector_pos
此时,玩家已经可以推动箱子了。
剩下的就是实现spot的Area2D在body_entered之后,进入下一关或弹出获胜对话框。
这样一个简单的推箱子游戏的核心就有了,就看你如何做出有趣的关卡了。