How to place something at a specific distance given a direction vector?

Godot Version

Godot 4.2

Question

I’m making a top down 2d arpg. I’m trying to make a melee swing ability. I have the swing animation and hitbox stuff set up. When you press the button, the swing should happen in the direction of the mouse. The problem was that if I just start it at the player’s position, the sword will be inside the player at it’s origin. So I’d need to make it appear at some distance just outside the player.

After thinking about it, the solution here is probably just to make a pivot point node on the player scene to spawn it at. But I figure it might be still useful to know how to do the original question:

Given a vector, how do you place an object at a certain distance along that vector? Just multiplying by the distance you want would presumably give the wrong answer. I figure I’d need to use a^2+b^2 = c^2, but I want the 2 sides I don’t know.

What is the proper math here and does godot have a simple way to calculate this or do I just need to add in the formulas?

You can divide the vector by its length and multiply by the desired distance.

vector.normalized() * DISTANCE

and it’s practically the same as

vector * (DISTANCE / vector.length())
1 Like

This is correct, the 2 sides you are using is the vector’s X and Y component to form a right triangle. The pythagorean theorem on a vector alone will result in it’s length (squared). This length is used to normalize the vector, dividing each component forms a ratio of the length from 0 to 1, or a direction. Maybe you got the direction value from a position.direction_to(mouse_position), which uses the same formulas. Now if you multiply each direction component by your distance you will get a vector with a length matching the distance provided and pointing in that direction.

tldr: what @grulps said

1 Like