如何使精灵沿一个方向移动,具体取决于鼠标的位置?

问题描述 投票:0回答:1

我正在寻找一个精灵(更具体的说是子弹),通过单击鼠标左键从另一个精灵(枪的末端)出来,然后让子弹朝着鼠标所在的方向移动过去,然后在点击发生后不改变位置。我解释得很糟,但是基本上我是在寻找要沿着鼠标方向移动的项目符号,一旦单击鼠标,就不会改变位置并跟随该方向,直到它离开屏幕为止。我正在尝试做的一个很好的例子是射击和子弹在名为Terraria的游戏中的工作方式。

我一直在尝试使用Position2D找出答案。我在枪的末端安装了Position2D,我希望将子弹装入该枪中。我也尝试通过Google和Youtube进行研究。现在,我有一个随鼠标位置旋转的精灵(手臂),还有一个附着在手臂上的精灵(枪)。我正在尝试使用手臂信息来找到方向,但是我无法弄清楚。我是一个一般的编码初学者。

这是我的手臂根据鼠标位置旋转的代码:

extends Sprite
var Mouse_Position


func _process(delta):
    Mouse_Position = get_local_mouse_position()
    rotation += Mouse_Position.angle()*0.2  

当前用于我的项目符号的代码是:

extends Area2D

const SPEED = 100
var velocity = Vector2()

var Mouse_Position




func _physics_process(delta):
    velocity.x = SPEED * delta
    Mouse_Position = get_local_mouse_position()
    rotation += Mouse_Position.angle()*0.2
    translate(velocity)

func _on_VisibilityNotifier2D_screen_exited():
    queue_free()


这里还有一些额外的东西可以加载到其中:

const BULLET = preload("res://Bullet.tscn")

    if Input.is_action_just_pressed("shoot"):

        var bullet = BULLET.instance()
        get_parent().add_child(bullet)
        bullet.position = $Position2D.global_position
2d godot gdscript
1个回答
0
投票

您需要为实例之前的方向设置一个变量,并且在调用_ process函数时不要更改它:

类似这样的东西:

extends Area2D

const SPEED = 100
var velocity = Vector2()
export (int) var dir # <--- Add this variable to modify the direction of the bullet from outside of the scene
var Mouse_Position


func _physics_process(delta):
   $Sprite.position += Vector2(SPEED * delta, 0.0).rotated(dir)
   $Sprite.global_rotation = dir  # Set the rotation of the Bullet


func _on_VisibilityNotifier2D_screen_exited():
    queue_free()

并且当您实例化项目符号时:

var bullet = BULLET.instance()
bullet.dir = $Sprite.global_rotation # <-- Assgin the rotation of the player to the bullet
get_parent().add_child(bullet)
bullet.position = $Sprite/Position2D.global_position # <-- Start the Bullet on the position2D

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.