Hold and move using mouse left click

In my game , I want to move the characterbody2d using mouse click and hold inbetween staticbody2d, I mean when I left click the characterbody2d and hold the left click then move the mouse while the characterbody2d move with that mouse at the same time inbetween staticbody2d, how to implement that in gd script, many tutorials covers click and move but there is no clear tutorial about click and hold the mouse to move characterbody2d inbetween staticbody2d, please help
Thanks in advance

what do you mean by inbetween staticbody2d

1 Like

From what I can tell, you want a drag and drop with collision.
First things first, does your staticBody2D have a collision shape? If not, you need to add one. The collisionShape2D documentation can be found here. You will also need a collisionShape2D for your player.

For the interesting part: Add a raycast2D node under the player and use a script to point it at the mouse and set the length to be the distance to the mouse. Then, every frame, probably under _physics_process, if the mouse is down and not just pressed (you will check for if it is just pressed AND is touching the player elsewhere), check if the raycast2D is colliding with a wall.
If so, set velocity to the mouse position - player position (might be the other way around) and call move_and_collide. This should shoot the player toward the mouse and have it stop when it hits the wall
if not, this means there is an open space where the player could probably fit, and you should set the player position to the mouse position.

I hope this helps.

1 Like