Simple jump code 2D - c#

Hi again, I’m in need of to get my character to jump with the animation or a tutorial that can help. BTW its 2D so I’m not sure if the FPSwalker assest script (I think that’s its name) will work.

Here’s my code so far:

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

	public float speed = 6.0f;

	public float jumpSpeed = 20f;

	public float gravity = 1f;

	Animator anim;

	void Start()
	{
		anim = GetComponent<Animator> ();
	}

	void Update()
	{
		PlayerController ();
	}
	
	void PlayerController()
	{
		anim.SetFloat("speed", Mathf.Abs(Input.GetAxis ("Horizontal"))); //setting the float parameter called "speed" depending on the input from the horizontal axis

		if(Input.GetAxisRaw("Horizontal") > 0) // if d or right key is pressed
		{
			transform.Translate(Vector3.right * speed * Time.deltaTime); //move right 4 pixels at a fixed framerate
			transform.eulerAngles = new Vector2 (0,0);
		}
		if(Input.GetAxisRaw("Horizontal") < 0) //if a or left key is pressed
		{
			transform.Translate(Vector3.right * speed * Time.deltaTime);
			transform.eulerAngles= new Vector2(0,180); //rotates gameobject by 180 degrees horizontally
		}
	}
}

You should use a Rigidbody2D component with gravity on your game object. Then you can use Rigidbody2D.AddForce to jump. To move side to side use Rigidbody2D.velocity. It would look like this

FixedUpdate()
{
   if (jump)
   {
      rigidbody2d.AddForce(new vector2(0, jumpForce));
   }

   rigidbody2d.velocity = new vector2(speed,    rigidbody2d.velocity.y);
}

I would recommend that you switch to Rigidbody2D anyway because you will run into problems using Transform.translate

If you need more help with how Rigidbody2D works feel free to ask me.

P.S. You definitely want your physics code in FixedUpdate()