从鼠标位置减去玩家位置向量,您将得到一个从玩家指向鼠标的向量。然后,您可以使用矢量的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)
Run Code Online (Sandbox Code Playgroud)
我在本例中使用 aKinematicBody2D作为Projectile.tscn场景,并使用 移动它move_and_collide(vel),但您也可以使用其他节点类型。另外,调整碰撞层和遮罩,使射弹不会与玩家碰撞。