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

there is an many walls which is staticbody2d , I need to move characterbody2d using mouse click and hold , then the character moves along with that holding left click moving mouse
Screenshot 2024-05-17 073030
that blue coin in this picture is an characterbody2d , I controlled its movement using keyboard input, but I also want to move with the mouse left click hold and move, that’s way asking, I watched many tutorial but when I implement that in this , there is wrong output because of staticbody2d in also there .(wall is the staticbody2d),please help
Thanks in advance

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