Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Godot make item follow mouse

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.

like image 222
Litsabber Dudeguy Avatar asked Aug 25 '18 14:08

Litsabber Dudeguy


2 Answers

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())
like image 76
Gustavo Kaneto Avatar answered Oct 24 '22 15:10

Gustavo Kaneto


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.

like image 2
skrx Avatar answered Oct 24 '22 13:10

skrx