Godot使项目跟随鼠标

时间:2018-08-25 14:37:55

标签: 2d mouse godot gdscript

我正在Godot 3.0中制作2D平台游戏,我希望玩家使用鼠标瞄准(类似于Terraria中的弓箭和枪械)投掷/射击物品。我将如何去做呢?我正在使用gdscript。

2 个答案:

答案 0 :(得分:2)

您可以使用look_at()方法(Node2DSpatial类)和get_global_mouse_position()

func _process(delta):
    SomeNode2DGun.look_at(get_global_mouse_position())

答案 1 :(得分:1)

从鼠标位置减去玩家位置向量,您将获得一个从玩家指向鼠标的向量。然后,您可以使用向量的angle方法来设置弹丸的角度并对其进行归一化,然后将其缩放到所需的长度以获取速度。

extends KinematicBody2D

var Projectile = preload('res://Projectile.tscn')

func _ready():
    set_process(true)

func _process(delta):
    # A vector that points from the player to the mouse position.
    var direction = get_viewport().get_mouse_position() - position

    if Input.is_action_just_pressed('ui_up'):
        var projectile = Projectile.instance()  # Create a projectile.
        # Set the position, rotation and velocity.
        projectile.position = position
        projectile.rotation = direction.angle()
        projectile.vel = direction.normalized() * 5  # Scale to length 5.
        get_parent().add_child(projectile)

在此示例中,我使用KinematicBody2D作为Projectile.tscn场景,并使用move_and_collide(vel)移动它,但是您也可以使用其他节点类型。另外,调整碰撞层和蒙版,以使弹丸不会与玩家碰撞。

相关问题