Object Velocity with mouse movement

v4.2.1.stable.mono.official [b09f793f5]


The problem I’m having is that there is no velocity when I release the mouse button
I’m trying to make something for a game jam and I have a system where if I grab the rigid body you can move its position with the mouse, but I’m trying to create velocity with the movement like air hockey.
I thought if I used a timer I could get the position at the start of the timer and then get it at the end subtract it and add it to the velocity but it won’t work. Im prob just dumb, anything will help.

This is my code so far,


extends RigidBody2D

var selected = false
const FOLLOW_SPEED = 100
var start_pos: Vector2
var end_pos: Vector2
var bag_vel: Vector2
func _physics_process(delta):
	var mouse_pos = get_global_mouse_position()
	if selected == true:
		%RigidBody2D.global_position = global_position.lerp(mouse_pos, delta * FOLLOW_SPEED)

func _integrate_forces(state):
	if Input.is_action_just_released("left click") and selected:
		selected = false
		%Timer.autostart = false
		var bag_vel = start_pos - end_pos
	bag_vel += %RigidBody2D.linear_velocity * 1000

func _on_area_2d_input_event(viewport, event, shape_idx):
		if Input.is_action_pressed("left click"):
			selected = true
			if %Timer.is_paused():
				start_pos = global_position
			%Timer.paused = false
			%Timer.autostart = true
			selected = false

func _on_timer_timeout():
	end_pos = global_position

The following alternative approach comes to mind:

When you receive an InputEventMouseMotion, you could access its InputEventMouseMotion.velocity and base your calculations on that.

1 Like