Click a rigidbody with the mouse

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Fabi1309
:warning: Old Version Published before Godot 3 was released.

Hey guys,

I am trying to create a game where u have to touch a ball and then the ball bounces up and then u have to touch it again, etc…

But how can I make it possible that I can click this rigidbody?

I created a rigidbody node and added a Sprite node (with the texture) and a CollisionShape2d node to it.
The ball now just falls down. I can use rigidbody.apply_impulse to make it “bounce” but how can I check when and where (on the left side or on the ride side) it is clicked!

I hope u understand what I want!

Greetings Fabi1309

PS: I am german…

:bust_in_silhouette: Reply From: PixelWizzard

Hello Fabi,
In the rigid body properties, there is an option called “pickable” (under “CollisionObject2D”). If you enable this option, your rigid body should be able to detect, if the mouse is inside its collisoin shape and react to these events via signals. Signals are functions, that get called under certain circumstances, like, in your case, if you click on the object with your mouse.

Thank u! But now the problem is it is just reacting when I enter the shape with my mouse not when I click it! How can I fix that?

Edit: Nevermind I got it

Fabi1309 | 2016-03-23 16:20

Well, I threw this code together:

func _input_event(viewport, event, shape_idx):
if(event.type == InputEvent.MOUSE_BUTTON and event.button_index == 1 and event.is_pressed() and !event.is_echo()):
	#assuming you want the object to move upwards:
    self.set_linear_velocity(Vector2(0, -300))

this should work

PixelWizzard | 2016-03-23 16:34

:bust_in_silhouette: Reply From: Fabi1309

Okay, I got this now… But does anybody has an Idea how can I check where the rigidbody is clicked so that I can set the impulse in the right way.

That means: If I click on the left side of the ball, the ball will fly to the right, etc…

Any ideas?

What you should do in this case is calculating the difference between your mouse cursor position and the center of your rigidBody and apply a velocity depending on that vector.
Somewhat like this:

func _input_event(viewport, event, shape_idx):
if(event.type == InputEvent.MOUSE_BUTTON and event.button_index == 1 and event.is_pressed() and !event.is_echo()):
	var direction = (self.get_pos() - get_global_mouse_pos()).normalized()
	self.set_linear_velocity(direction * speed)

PixelWizzard | 2016-03-23 16:38

Thank u so much! It’s working I just had to change a few things so that it fits better into the game!

Fabi1309 | 2016-03-23 16:42