0
\$\begingroup\$

I am making a 2D game where the character rides on the curve of a graph. I need to find out whether the player is going uphill or downhill and calculate speed accordingly.

The problem is that I am not sure how to determine the slope of the curve on the point that the character is at.

Here is an example of what some of the curves look like: blue circle is the player

\$\endgroup\$
  • 1
    \$\begingroup\$ Can you how us how you generate / load your curves? \$\endgroup\$ – DMGregory May 13 '18 at 20:55
  • 1
    \$\begingroup\$ @DMGregory I get curves from a file contain x y coordinate pairs in a JSON array. I then generate curves by iterating through the array and drawing a bezier curve through every 3 points. \$\endgroup\$ – DataPools May 14 '18 at 4:02
2
\$\begingroup\$

Since you use a quadratic Bezier curve to interpolate between threee consecutive points, you can simply use the derivative of the Bezier curve to find the tangent to the curve at a point.

The derivative of the quadratic Bezier curve interpolating between the points p0, p1 and p2 is

B'(t) = 2(1 - t)(p1 - p0) + 2t(p2 - p1)

Simply plug in the value of t for the point at which the slope is to be calculated to get a vector tangent in direction of the tangent. The slope of the curve at that point is tangent.y / tangent.x.

\$\endgroup\$
  • \$\begingroup\$ What do I plug in for t? Is it the x coordinate on the curve that I want to calculate slope at? \$\endgroup\$ – DataPools May 14 '18 at 23:26
  • \$\begingroup\$ You would put in the same value for t as the one you would put in the original Bezier equation to find the position of the point the ball is currently on. \$\endgroup\$ – EvilTak May 15 '18 at 9:25
0
\$\begingroup\$

Differentiate it

If your curve is based on a static formula, then just plug that into Wolfram|Alpha, find the one labelled as "Derivative" and that should give you a formula, which determines the slope of the curve at x. Plug the x position of the player in the curve's coordinate system and you get the slope. A value of 5 for instance means it goes up 5 units if you go 1 unit on the x axis.

If you can't do that, because it's procedural, then fake it. Pick a very small value (>0.001 will do it) and get the height of the curve at the player's position, then add this small value to the x coordinate and get the height there too. Subtract the former from the latter and divide by the small value. This is a good estimate (derivation is basically this but with a distance of 0). This won't really work if you predefine the heights, since that wouldn't leave you with enough precision.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.