刚开始学习 Godot,并且遇到了 2D Raycast 向左而不是向右或向右而不是向左的问题。
所以我有一个基本的自上而下的 2D 游戏,在播放器上带有光线投射。朝上和朝下工作得很好,只是左和右会引起头痛。代码看起来不错,所以这就是我在这里的原因
onready var rayCast = get_node("RayCast2D")
func _physics_process(delta):
vel = Vector2()
# inputs
if Input.is_action_pressed("move_up"):
vel.y -= 1
facingDir = Vector2(0, -1)
if Input.is_action_pressed("move_down"):
vel.y += 1
facingDir = Vector2(0, 1)
if Input.is_action_pressed("move_left"):
vel.x -= 1
facingDir = Vector2(1, 0)
if Input.is_action_pressed("move_right"):
vel.x += 1
facingDir = Vector2(-1, 0)
vel = vel.normalized()
move_and_slide(vel * moveSpeed)
manage_animations()
func manage_animations ():
if vel.x > 0:
play_animation("MoveRight")
elif vel.x < 0:
play_animation("MoveLeft")
elif vel.y < 0:
play_animation("MoveUp")
elif vel.y > 0:
play_animation("MoveDown")
elif facingDir.x == -1:
play_animation("IdleRight")
elif facingDir.x == 1:
play_animation("IdleLeft")
elif facingDir.y == -1:
play_animation("IdleUp")
elif facingDir.y == 1:
play_animation("IdleDown")
func _process(delta):
if Input.is_action_just_pressed("interract"):
try_interact()
func try_interact():
rayCast.cast_to = facingDir * interactDist
if rayCast.is_colliding():
if rayCast.get_collider() is KinematicBody2D:
rayCast.get_collider().take_damage(damage)
elif rayCast.get_collider().has_method("on_interact"):
rayCast.get_collider().on_interact(self)
我已经尝试在左右移动中更改 Vector2 x 和 y 变量,虽然这样可行,但步行就变得一团糟。
有任何想法吗?