.normalized() does not function as expected, can't get rigidBody2D to follow mouse smoothly


Hey, I’m trying to make an inventory system where you move items around a physical backpack space, items being rigid body 2Ds, problem is forces, the acceleration gets insane very quickly and can glitch out the collision the further away the mouse is from the object, which becomes an issue when collisions occur and quickly tunneling can happen. Two items colliding is also pretty funny. Now I know why this is happening, the velocity gets insanely high because its multiplying the distance by 50 and setting that as the speed, so my “solution” well I tried to use get_local_mouse_position().normalized(), works, sorta but just kinda jitters around the mouse when it reaches it so not great. If anyone knows a better way to do this (physics are janky if I freeze and set the transform to the mouse)

Heres the code:
extends RigidBody2D

var Mouse_Inside = false
var held = false
const SPRING_CONSTANT := 1000.0

Called when the node enters the scene tree for the first time.

func _ready():
$CollisionShape2D.disabled = false

Called every frame. ‘delta’ is the elapsed time since the previous frame.

func _physics_process(delta):

if Input.is_action_just_pressed("Click") and Mouse_Inside == true:
	held = true
elif Input.is_action_just_released("Click"):
	held = false


if held == true:
	set_collision_mask_value(3, false)
	lock_rotation = true
	linear_velocity = get_local_mouse_position() * 50
	set_collision_mask_value(3, true)
	lock_rotation = false
	$CollisionShape2D.disabled = false
if held == true and Input.is_action_just_pressed("rotate"):
	rotation_degrees += 90

func _on_area_2d_mouse_shape_entered(shape_idx):
Mouse_Inside = true

func _on_area_2d_mouse_shape_exited(shape_idx):
Mouse_Inside = false

Don’t modify the RigidBody2D directly as the physics system will override it and cause issues. Use the RigidBody2D._integrate_forces() callback and modify its state argument instead.

Using normalized() should work fine. The problem is that it overshoots the mouse in one frame and tries to compensate it back in the next frame. That’s why it’s jittering. You’ll need to give it some buffer zone where you don’t want to apply any modification to the node so it stops.

1 Like

I figured overshooting might have been the case, I “solved” it by just capping the maximum velocity which prevented tunneling but was a pretty bandaid solution, I’ll implement yours. Thanks!