+2 votes

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...

asked Mar 23, 2016 in Engine by Fabi1309 (30 points)

2 Answers

0 votes
Best answer

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.

answered Mar 23, 2016 by PixelWizzard (212 points)
selected Mar 23, 2016 by Fabi1309

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

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

+1 vote

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?

answered Mar 23, 2016 by Fabi1309 (30 points)

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)

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.