Godot Version
Godot 4.5 dev4
Question
Hi ! I have in my project a character that moves horizontally. Besides of that, I have a object moving on a rail.
What I want is to have the rail object to follow exactly the x position of the player, while still moving along the rail normal., like that :
How can I do that ? I’ve looked at the docs, but didn’t help me that much.
Hi,
You could try calculating the intersection point between the segment of the rail, and a segment going from the player position to a point far below the player (far enough so that you’re sure it will be below the rail, ensuring an intersection). You’d also need a starting point and a end point of the rail, but I suppose you can calculate those easily if you don’t have them already.
Here’s a function in GDScript computing the intersection of two segments A and B:
func computeSegmentsIntersection(a1: Vector2, a2: Vector2, b1: Vector2, b2: Vector2) -> Vector2:
var d: float = (a2.x - a1.x) * (b2.y - b1.y) - (a2.y - a1.y) * (b2.x - b1.x);
if d == 0:
return Vector2(INF, INF);
var u: float = ((b1.x - a1.x) * (b2.y - b1.y) - (b1.y - a1.y) * (b2.x - b1.x)) / d;
var v: float = ((b1.x - a1.x) * (a2.y - a1.y) - (b1.y - a1.y) * (a2.x - a1.x)) / d;
if u < 0 or u > 1 or v < 0 or v > 1:
return Vector2(INF, INF);
return Vector2(a1.x + u * (a2.x - a1.x), a1.y + u * (a2.y - a1.y));
Let me know if that works for you.
2 Likes
Thank you @sixrobin, the piece of code you’ve shared with me was the perfect solution for my problem.
Thank you very much for your help, I appreciate it a lot, and I’ll mention you in my game credits
.
1 Like