- Home /
jump on collision weird behaviour
Hello I have this script below. I want only to move the character left or right and when he collides to give him a jump effect. It seems to work fine. But when the character collides and its on the air and collides again with a new object of same type the jump effect is doubled or tripled and its not like the normal one. If it collides with the same object again the jump effect is back to normal. Anyone knows whats wrong?
var speed : float = 5;
var height : int = 150;
var x : float;
public var distanceTravelled : float;
function OnCollisionEnter( collision : Collision ) {
rigidbody.AddForce (Vector3.up * height);
}
function Start () {
}
function Update () {
x = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
transform.Translate(x, 0, 0);
distanceTravelled = transform.localPosition.y;
Debug.Log("Distance:" + distanceTravelled);
}
Answer by Heav3n · Nov 11, 2012 at 02:56 PM
I did it with
rigidbody.velocity
instead of rigidbody.AddForce
and seems to work like i want :)
Thanks for the help
Answer by KiraSensei · Nov 11, 2012 at 12:33 PM
On each collision you add a force. Instead of adding a new force, you need to "forget" the old force you applied first. You can add the opposite force to the old one before adding the new one for example. I don't see any method to do it easier. If someone knows one ...
Thanks for your answer. Could you explain with code where do I need to "forget" about it?
You can "store" the previous force you applied in a variable, and when another force must be applied, just before you add the opposite of the previous force. It is only a trick to easily bypass the problem. There should be a smoother solution but I don't know it :)
var firstTime : boolean = true;
function OnCollisionEnter( collision : Collision ) { if (firstTime) { rigidbody.AddForce (Vector3.up height); } else { rigidbody.AddForce (Vector3.down height); rigidbody.AddForce (Vector3.up * height); firstTime = false; } }