Box not jumping, just jitters like it's stuck to the ground (2D platformer movement)

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:

Is a RigidBody attached to this object?

1 Answer

1

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.

And of course, the amount of force you apply is dependent on the mass of your RigidBody (if you're using that). Since you're using OnCollisionEnter, I assume you are.

That worked great, thanks. :D I wasn't aware of this function before, I guess I have some reading up to do on vector operations. :P (Also sorry I was slow to respond, I was away for a couple of days, didn't think I'd get an answer so fast)