我正在 Godot 3.5 中制作 2d 跑步游戏,射击是其中的一个组成部分
一切正常,但子弹定位存在技术问题。一般来说,我对编码也比较陌生,所以最好相信我已经尝试了所有处理它的方法。
当我单击选项卡按钮时,项目符号会堆叠在顶部,如图所示。我希望它从玩家的位置射击。我不知道如何解决这个问题。任何建议将不胜感激。
const UP = Vector2(0, -1)
const SPEED = 200
const GRAVITY = 20
const JUMP_HEIGHT = -690
var motion = Vector2() # moving in 2d space
func _physics_process(_delta):
motion.y += GRAVITY
if Input.is_action_pressed("ui_right"):
$Sprite.flip_h = false # Do not flip the sprite
motion.x = SPEED
elif Input.is_action_pressed("ui_left"):
$Sprite.flip_h = true # Flip the sprite to face left
motion.x = -SPEED
else:
motion.x = 0
# Play appropriate animation based on character's movement
if motion.x != 0: # If character is moving
$Sprite.play("Run")
else:
$Sprite.play("Idle") # Match the play actions to the names of the animation states
if is_on_floor():
if Input.is_action_pressed("ui_up"):
motion.y = JUMP_HEIGHT
else:
if motion.y < 0:
$Sprite.play("Jump")
print("jump")
else:
$Sprite.play("Fall")
print("fall")
# use move_and_slide to create movement on screen
motion = move_and_slide(motion, UP)
# bullets
const SHOOT_SPEED = 300
var bulletscene = preload("res://Shoot.tscn")
func _process(delta):
if Input.is_action_just_pressed("ui_accept"):
shoot()
$Node2D.look_at(get_global_mouse_position())
func shoot():
var bullet = bulletscene.instance()
get_parent().add_child(bullet)
bullet.position = $Node2D/Position2D.position
bullet.velocity = get_global_mouse_position() - bullet.position
首先,正如我在你的图片中看到的,Shoot场景到处都有Sprite2D和CollisionShape2D。这可能会导致奇怪的图形错误。您应该确保它们的变换位置和偏移量设置为
0
本地场景中的两个轴。
其次,
position
属性用于表示在本地场景中的相对位置。您应该使用 global_position
复制玩家的 Position2D。
func shoot():
var bullet = bulletscene.instance()
get_parent().add_child(bullet)
bullet.global_position = $Node2D/Position2D.global_position
bullet.velocity = get_global_mouse_position() - bullet.global_position