Hello guys. So I wanna make an endless runner game in unity but I can not figure out the coding for the movement I want to be able to jump while my character is moving constantly forward. I got the code for the moving forward part but I can not figure out the code for the jumping. Could someone help me out please?
using UnityEngine;
public class movementcontroller : MonoBehaviour
{
void Update()
{
transform.Translate(5f * Time.deltaTime, 0f, 0f);
}
}
Yeah! I have similar movement in a game I’m working on. One easy way to do jumping is with physics. If you add a Rigidbody2D to your player, you can easily do a jump by adding force to the rigidbody. Add that component to your character and try this code:
using UnityEngine;
public class movementcontroller : MonoBehaviour
{
void Update()
{
transform.Translate(5f * Time.deltaTime, 0f, 0f);
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<RigidBody2D>().AddForce(Vector2.up * 20f);
}
}
}
In this example, the values that go in the AddForce parameter are the direction and power of the force you’re adding. Vector2.up is (0, 1) which means straight up! And you can replace 20f with however powerful you want the jump to be, depends on how heavy the player is, etc
Press lock rotation on the RigidBody component on x, y, and z! It looks like the jump is working but the character is flopping around because the rotation isn’t locked.
Beware of mixing Transform.Translate() with Rigidbody (or Rigidbody2D).
By doing so you are bypassing the physics system and you will miss collision and trigger callbacks, plus collisions themselves will be glitchy and jerky.
Instead, ONLY use the .MovePosition() method on the Rigidbody if you are absolutely moving it.
Obviously, you can always add forces or set velocities as well. The above only applies to driving positions explicitly.
Translate just adds the numbers you insert to the transform’s position.
You have told it to add 5f * Time.deltaTime which is 5 * 0.016667 = 0.0833335 every frame to the X position, which means 5 units per second (0.0833335 * 60 frames).
For a jump, you want to make a number that goes go up when you push an input, but gets constantly subtracted from (simulating gravity), then use that as the Y input. It should be 0 when you are “grounded”. When it’s below 0 you will move down. When it’s above 0 you will go up.