0 votes

Hi guys!

First time ever coding a game (or coding in general), and I've been learning lots. I've been trying to get a ball to move towards the coordinates where my mouse has clicked. I don't really quite understand all the vector things yet, so I'm having trouble with what's happening here.

func _input(event):
if event.is_pressed(): # Mouse click coordinates
    velocity.x = event.position.x - global_position.x
    velocity.y = event.position.y - global_position.y

So far, the event.position gets the coordinates where my mouse presses. Yay!
The ball goes in the right direction, but at an insane speed. Any tips? Thank you!

in Engine by (27 points)

1 Answer

+1 vote
Best answer

Look at this tutorial:

Godot 2d movement tutorial

Generally, velocity is the distance added to your ball. You calculate the distance between the cursor and the ball and then you add it to the ball position, that's why the ball runs so fast - you make it move directly to the cursor position.
You should normalize the distance to find the direction, then multiply it by the wanted speed and by the delta time passed.

by (58 points)
selected by
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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.