public class spring : MonoBehaviour
{
[SerializeField] public float jumpHeight = 10f;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
collision.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight, ForceMode2D.Impulse);
}
}
}
I’ve made an upwards spring and it was pretty easy to make, I thought it’d be as easy to make a sideways spring but I’m having no luck right now. The script above is said upward spring script. I also know that I have to do something with direction since the player would be going toward the spring to hit it, then get shot back.
I’ve tried to adapt my upward spring script so that you go in the direction specified in the script (for example, Vector2.right
to go right) but I’m guessing it simply doesn’t and can’t work that way. All the posts I’ve seen online when trying to solve my issue seem to either be about something else in unity coincidentally called a spring, or how to push an object as the player
edit:
the actual results for Vector2.right
doesn’t change the direction, it just bounces the player anyway. Also, I renamed the jumpHeight variable to rightForce, but I’m sure that has nothing to do with it not working. Unity showed no errors
2
Let’s improve it !
We will use tranform.up as the direction (This is the green arrow you can see when you select the gameobject)
Make sure that your spring sprite point toward this green arrow.
Then simply change your script to use tranform.up
public class spring : MonoBehaviour
{
[SerializeField] public float jumpForce = 10f;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
collision.gameObject.GetComponent<Rigidbody2D>().AddForce(transform.up * jumpForce , ForceMode2D.Impulse);
}
}
}
Note : This “spring” script should be at the root of your spring, not in a child.
Now if you rotate your spring it should correctly send your player in the same direction as the green arrow 🙂
Don’t forget that there is physical friction between your character and the ground so you might need to increase the force of the horizontal spring to counter that.
Edit : I just saw derHugo comment’s. He’s right, be careful not to overwrite the spring force with your inputs.
You cant write let’s say :
rigibody.velocity = someComputedVelocity
This “=” will overwrite the forces