0 votes

Hi, I'm learning Godot3. I want to control a KinematicBody2D with my mouse. I understand how to move my object with the mouse like this

var mouse = get_viewport().get_mouse_position()
set_position(Vector2(mouse.x, position.y))

However I want to controll the speed of my object. So I can frustrate the user with a slow movement.

First thought is to capture the mouse and be able to set the speed of the mouse. But I don't see anything for that.

I looked in to InputEventMouseMotion but can't find how to use it.
In the docs there is a setspeed. But InputEventMouseMotion.setspeed won't work.

Could somebody explain me this basic controll?

in Engine by (75 points)

1 Answer

+1 vote

Apparently getspeed() works similar to getlinear_velocity() for physics bodies, but not exactly. That means, you can't directly slow down the mouse, which is logical btw, because it's movement is handled by the OS. What I would do with KinematicBody2D is this:

func _input(event):
    if event is InputEventMouseMotion:
        var speed = event.get_speed()
        var new_speed = event.set_speed(speed * 0.1)
        KinematicBody2D.set_linear_velocity(new_speed)

Now, your player will follow the movement of your mouse, scaled down by 10.

by (840 points)

event.get_speed always return (0,0) no mater the speed I of the mouse.

If I do event.as_text() it returns this:

InputEventMouseMotion : button_mask=0, position=(28, -6), relative=(0, -1), speed=(0, 0)

You see the speed is alway 0,0

Here is how i do it now... Maybe you can give me some pointers?

extends KinematicBody2D

var speed = 8
var max_mouse_speed = 8
var new_speed = Vector2()
var move = Vector2()

func _ready():
    set_process_input(true)
    Input.set_mouse_mode(1)

func _input(event):
    if event is InputEventMouseMotion:
        var rel = event.get_relative()
        if rel.x > max_mouse_speed:
            rel.x = max_mouse_speed
        elif rel.x < -max_mouse_speed:
            rel.x = -max_mouse_speed

        print(rel.x)
        self.move_and_collide(Vector2(rel.x,0))



func _process(delta):
    if Input.is_key_pressed(KEY_LEFT):
        move.x = -1

    elif Input.is_key_pressed(KEY_RIGHT):
        move.x = +1
    else:
        move.x = 0

    move_and_collide(Vector2(move) * speed)

    if Input.is_key_pressed(16777217):
        get_tree().quit()
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.