I am making a 2D platformer in Godot 3.0 and I want to have the player throw/shoot items using the mouse to aim (similar to bows and guns in Terraria). How would I go about doing this? I am using gdscript.
You can use look_at()
method (Node2D
and Spatial
classes) and get_global_mouse_position()
:
func _process(delta):
SomeNode2DGun.look_at(get_global_mouse_position())
Subtract the player position vector from the mouse position and you'll get a vector that points from the player to the mouse. Then you can use the vector's angle
method to set the angle of your projectiles and normalize the vector and scale it to the desired length to get the velocity.
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)
I'm using a KinematicBody2D
as the Projectile.tscn
scene in this example and move it with move_and_collide(vel)
, but you can use other node types as well. Also, adjust the collision layers and mask, so that the projectiles don't collide with the player.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With