我正在制作乒乓球,屏幕两侧各有两个球拍。最初,我使用的是
Input.get_vector()
,但这迫使我在只需要两个参数时接受 4 个参数。我也尝试过使用 Input.get_axis()
但我无法让它发挥作用。
现在我回到基础知识并开始使用
Input.is_action_pressed()
,因为它看起来不那么复杂,我使用move_and_collide()
结束了该功能,因为我需要中间的球从桨上弹开,但我不需要认为 move_and_slide()
是最好的选择。
当我运行代码时,它按预期工作,但即使将
speed
设置为 1
,桨的速度也非常快。另外,重力有点不稳定,即使我点击 up
箭头一次,桨也不会停止移动。
如何修复我的代码,以便当我放开箭头键时桨不会缩小屏幕并实际停止?
extends CharacterBody2D
var speed: int = 1
func _physics_process(delta):
if Input.is_action_pressed("p2_up"):
velocity.y -= speed
elif Input.is_action_pressed("p2_down"):
velocity.y += speed
move_and_collide(velocity)
首先,Godot 4 使用的单位是米和秒。因此,
1
的速度是每秒一米。
其次,
_physics_process
将在每个物理帧运行一次,默认情况下每秒运行60
次。
第三,如果按下操作,
Input.is_action_pressed
返回 true
,否则返回 false
。
因此,这里:
extends CharacterBody2D
var speed: int = 1
func _physics_process(delta):
if Input.is_action_pressed("p2_up"):
velocity.y -= speed
elif Input.is_action_pressed("p2_down"):
velocity.y += speed
move_and_collide(velocity)
只要按下该操作,您就会以每秒每米一秒的速度递增/递减速度,即每秒 60 次。
因此,角色身体在一秒钟内从零加速到每秒 60 米(134.2 英里每小时或 216 公里每小时)。
而且你永远不会重置速度。
我相信您打算设置速度而不是递增/递减它:
extends CharacterBody2D
var speed: float = 1.0
func _physics_process(delta:float) -> void:
if Input.is_action_pressed("p2_up"):
velocity.y = - speed
elif Input.is_action_pressed("p2_down"):
velocity.y = speed
else:
velocity.y = 0.0
move_and_collide(velocity)
如果你想支持模拟输入,你可以使用
get_action_strength
...但是更容易使用get_axis
:
extends CharacterBody2D
var speed: float = 1.0
func _physics_process(delta:float) -> void:
velocity.y = Input.get_axis("p2_up", "p2_down")
move_and_collide(velocity)
使用
get_vector
在这里没有任何意义,因为它只是一个轴。
你说重力是靠不住的,但有问题的代码没有重力。
您负责
CharacterBody2D
的运动,其中包括实现重力。
您可以自己实现重力和弹跳。但是,如果您想创建一个其他事物可以推送的对象,请考虑使用
RigidBody2D
代替。如果你这样做,戈多将为你处理重力和弹跳,而你必须通过添加力和冲量来控制它。