1
\$\begingroup\$

I want to add springs in my game that work like the ones in sonic - i.e. if you can't get over an obstacle you have to hit a spring which sends the main character flying towards another spring that gets him over that obstacle. I drew a little diagram below to demonstrate what I mean (yellow arrows represent the direction the player will go towards and the red - are the springs). enter image description here

In my Spring class I have created a method:

//The detection area (blue rectangle in the diagram)
public Rectangle broadPhaseDetection() {
        broadPhaseRectangle = new Rectangle(getxPos() - broadPhaseLength, getyPos(),
        broadPhaseLength, broadPhaseLength);
        return broadPhaseRectangle;
    }

If the Player collides with a Spring, I check to see if there's ANOTHER Spring within the blue area and if there is - calculate the vector that takes you towards that spring and send the player in that direction.

This seems like a very simple concept which has probably been done loads of times before, but I couldn't find any good examples online for some reason. Does anybody know how I can get the vector I need?

Any insight is highly appreciated, thanks.

\$\endgroup\$
  • \$\begingroup\$ Rather than detecting another spring in a vicinity, it would be easier to simply manually link the 2 springs together as they're static entities on the map. \$\endgroup\$ – d3dave Mar 8 '15 at 0:05
2
\$\begingroup\$

Calculating the vector that points from a spring at point A = (x0, y0) to a spring at point B = (x1, y1) is simply:

v = (x1 - x0, y1 - y0)

Assuming no other forces acting on the player, then changing the player's velocity to some scalar multiple of v when they hit spring A would direct them to spring B.

If another force like gravity is involved, then, depending on the type of movement you're looking for, you might want to disable gravity for the duration of travel from spring A to B, or adjust their new velocity vector to account for gravity.

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