InputEventMouseMotion

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Enquest

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 set_speed. But InputEventMouseMotion.set_speed won’t work.

Could somebody explain me this basic controll?

:bust_in_silhouette: Reply From: Footurist

Apparently get_speed() works similar to get_linear_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.

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

Enquest | 2018-02-18 19:27

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()

Enquest | 2018-02-18 20:00