Character falls through spring (and floor sometimes)

Hi guys,

could anyone help me out here?

When my character touches a spring object, he flies up into the air as expected, but when he comes back down again, he falls through the spring and does nothing, i then have to get my character to walk outside the object then back in again to activate it. what am i doing wrong?

using UnityEngine;
using System.Collections;

public class Spring : MonoBehaviour {

public GameObject player;
private Rigidbody RbPlayer;
public int springAmount;
//private bool springHit = false;

	// Use this for initialization
	void Start () {
		RbPlayer = player.GetComponent<Rigidbody>();
	}
	

	void OnTriggerEnter(Collider other)
 {
     if (other.tag == "Spring")
     {
        // springHit = true;

         RbPlayer.AddForce (new Vector3 (0, springAmount,0)); 

     }
 }


}

In order for AddForce to work, it needs to counteract the force of you coming down. This worked for me, you’ll probably have to tone down the amount of force you apply.

    void OnTriggerEnter(Collider other) {
        Debug.Log("JSDFJSDF");
        if (other.tag == "Spring") {
            // springHit = true;

            RbPlayer.AddForce(new Vector3(0, springAmount + Mathf.Abs(RbPlayer.velocity.y), 0), ForceMode.VelocityChange);

        }
    }

Your builds up velocity when he is falling. It works the first time, because you have no downward velocity. So you need to counteract the -y velocity. I tried to post this before but it got deleted.

RbPlayer.AddForce(new Vector3(0, springAmount + Mathf.Abs(RbPlayer.velocity.y), 0), ForceMode.VelocityChange);

You will need to reduce your spring amount. Let me know if you need more help.

Like Rhombuster said, while falling the AddForce will only slow you down. Try this to reset your falling velocity just before adding force:

void OnTriggerEnter(Collider other)
{
    if (other.tag == "Spring")
    {
    // springHit = true;
    Vector3 tempVelocity = RbPlayer.velocity;
    tempVelocity.y = 0;
    RbPlayer.velocity = tempVelocity;
    RbPlayer.AddForce (new Vector3 (0, springAmount,0)); 
    }
}

Or if the object on spring will always have same mass then you could just set y velocity instead of using AddForce.

void OnTriggerEnter(Collider other)
{
    if (other.tag == "Spring")
    {
    // springHit = true;

    RbPlayer.velocity = new Vector3 (RbPlayer.velocity.x, springAmount, RbPlayer.velocity.z); 
    }
}

OMG! you guys are great! thank you so much for explaining that and helping me out with he code, very much appreciated! :slight_smile: