Sorry if this has been asked before but I couldn’t find exactly what I wanted.
I’m trying to set up an object that will jump when the jump button is pressed. I want the button to instantly set upward velocity to the y vector but that I then slowly depreciate until natural gravity is a greater force and pulls the character back down to a surface to land.

Unfortunately what I’m getting is that the box I’m using to test doesn’t move up, it just jitters on the surface and then seemingly at random it leaps up huge distances, like it has just overcome the earth’s gravitational pull.

I’d be very much obliged if someone could explain where my code is flawed and leads to this. I know there are probably tutorials that could show me exactly how to do this but I’d like if I could understand what about this approach was failing.

Here’s my code:

#pragma strict
var speed: int;
private var distY: float = 0;
var artificialGravity: float;
var midair = false;
var jumping: float;
private var jumpingHeight: float;

function Update () {
	if(Input.GetButtonDown("Jump")){
		jumpingHeight = jumping;
		midair = true;
	}

	var distX = Input.GetAxis("Horizontal")*Time.deltaTime*speed;
	var distY = jumpingHeight*Time.deltaTime;
	
	jumpingHeight*=artificialGravity;
			
	transform.Translate(distX,distY,0);
}

function OnCollisionEnter(collision: Collision){
	if (!Input.GetButton("Jump")){
		midair = false;
		jumpingHeight = 0;
	}
}

Thanks in advance for anyone who can help. :slight_smile:

If your object is a RigidBody, you could just let Unity Physics do the work…

void Update () {
	
		if(Input.GetButtonDown("Jump"))
		{
			if(!midair)
			{
	    		rigidbody.AddForce(Vector3.up * 500);
				midair = true;
			}
	    }
	}

EDIT: Forgot you were using Javascript

function Update () {

	if(Input.GetButtonDown("Jump"))
	{
		if(!midair)
		{
	    	rigidbody.AddForce(Vector3.up * 500);
			midair = true;
		}
	}   
}

EDIT: Forgot to just use convenience property rigidbody.