# Creating Springs platforms in 2D

I’m a bit stuck on how to do this and I can use some help.
I’m writing a 2D game where I have spring platforms. What they need to do is bounce the player to a certain angle and a constant force. The best example I can think of are the springs in the early 2D sonic games.

What should happen is the player falls onto a spring and this needs to push the player. The angle which it should work is the rotation angle set in the editor. So if the spring faces up, the player should be pushed up, if the spring faces at an angle the player should be pushed at an angle. But the hard part is that the players velocity also needs to stay in tact some bit. If the player is moving right and down and landing on spring and the spring faces up, the right momentum needs to stay in tact.

What I have so far works but not good enough. I’m now calculating the angle of the spring and adding a force to the player. This keeps the players side momentum but also keeps the players down momentum. This means that if the player is moving downward too fast it will cancel out the force I’m adding from the spring. I’m not sure what to do next. I Could use the reflect option but that would mean that when the player hits the spring fast it also reflects fast. I Would like to a somewhat constant spring force.

This is the code I have now:

``````public void SpringActivate(Rigidbody2D rb)
{
GetComponent<Animator>().SetBool("Activate", true);
Vector2 directionVector = GetDirectionVector2D(270 + transform.localEulerAngles.z);
Vector3 force = (directionVector * -1) * springJumpBoost;
rb.AddForce(force, ForceMode2D.Impulse);
Debug.DrawRay(transform.position, (directionVector * -1) * 2, Color.blue, 0.2f);
}

public Vector2 GetDirectionVector2D(float angle)
{
return new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad)).normalized;
}
``````

I Think I solved my issue. This seems to be working well for me:

``````public void SpringActivate(Rigidbody2D rb)
{
GetComponent<Animator>().SetBool("Activate", true);
Vector2 directionVector = GetDirectionVector2D(270 + transform.localEulerAngles.z);
Vector2 force = (directionVector * -1) * springJumpBoost;
float fx = (force.x > 0) ? math.max(force.x, rb.velocity.x) : math.min(force.x, rb.velocity.x);
float fy = (force.y > 0) ? math.max(force.y, rb.velocity.y) : math.min(force.y, rb.velocity.y);
rb.velocity = new Vector2((fx == 0) ? rb.velocity.x : fx, (fy == 0) ? rb.velocity.y : fy);
//Debug.DrawRay(transform.position, (directionVector * -1) * 2, Color.blue, 0.2f);
}

public Vector2 GetDirectionVector2D(float angle)
{
return new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad)).normalized;
}
``````