extends CharacterBody2D
var mon = Vector2.ZERO
func _physics_process(delta):
mon = move_and_slide()
if Input.is_action_pressed("ui_left"):
mon.x = -1 # Set the horizontal speed to -1
elif Input.is_action_pressed("ui_right"):
mon.x = 1 # Set the horizontal speed to 1
else:
mon.x = 0 # Stop horizontal movement
错误是:“int”类型值的无效集“x”(基于“bool”)
我尝试了几个想法,请有人解释一下为什么以及移动和滑动的作用是什么,我是 GDScript 的初学者,我正在使用 C++ 学习 Sfml 请帮助我解决 Godot 问题
这里有两个有趣的点:
变量
mon
声明时没有类型:
var mon = Vector2.ZERO
这里变量用
Vector2.ZERO
初始化,但它是一个Variant。 Godot 不会阻止你设置不同类型的变量。
如果显式声明类型:
var mon:Vector2 = Vector2.ZERO
或者隐含地:
var mon := Vector2.ZERO
当你没有给它设置
Vector2
时,Godot 会告诉你。
方法
move_and_slide
返回一个bool
。
结果,这里:
mon = move_and_slide()
mon
变量被设置为 bool
值。
在 Godot 3.x 中
move_and_slide
用于返回具有最终速度的向量。在 Godot 4.x 中,情况不再如此。相反,move_and_slide
根据 velocity
属性移动,并且它还会更新所述 velocity
属性。
bool
返回的move_and_slide
值会告诉您是否存在碰撞。
话虽如此,您应该使用
velocity
:
extends CharacterBody2D
func _physics_process(delta):
move_and_slide()
if Input.is_action_pressed("ui_left"):
velocity.x = -1 # Set the horizontal speed to -1
elif Input.is_action_pressed("ui_right"):
velocity.x = 1 # Set the horizontal speed to 1
else:
velocity.x = 0 # Stop horizontal movement
我还要注意,2D 的
velocity
的单位是每秒像素数。因此将其组件设置为 1
意味着移动一个像素需要一秒钟,这太小了,不易注意到。
相反,请考虑声明速度:
extends CharacterBody2D
var speed := 100.0
func _physics_process(delta):
move_and_slide()
if Input.is_action_pressed("ui_left"):
velocity.x = -speed
elif Input.is_action_pressed("ui_right"):
velocity.x = speed
else:
velocity.x = 0
当然,将
speed
设置为你想要的。
奖励喋喋不休:你可以使用
get_axis
:
extends CharacterBody2D
var speed := 100.0
func _physics_process(delta):
move_and_slide()
velocity.x = Input.get_axis("ui_left", "ui_right") * speed
请注意,
get_axis
方法使用输入的强度,因此如果配置的话,它将对模拟输入(例如操纵杆)敏感。