I’ve made a 2D movement script but when i jump it is very jittery once the gravity kicks in and you’re still pressing W. Does anybody know how to smoothen it a bit?
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour{
public float moveSpeed = 10f;
void Update () {
float h = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
float v = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
transform.Translate (new Vector3 (h, v, 0));
}
}
You probably shouldn’t be modifying the transform yourself. Instead, act on the player’s Rigidbody (for instance, calling AddForce()). In this way, you will work within the physics system rather than fighting it.
Oh, rigidbody gravity. In that case, avoid translate(). In order to work with a rigidbody you should use forces to control the character. Another solution, usually frowned upon, is to alter the rigidbody.velocity property directly; I’m working in a 2d game and this approach isn’t giving me any trouble so far.
You’re manually changing the position, and the physics will give it velocity downwards, which increases over time (that’s how gravity works).
You could give yourself velocity upwards, and let the physics engine do the rest. That way you will have a realistic jump (starting fast, slowing down as you reach the peak, and then start gaining velocity downwards until you hit the ground). It also means the jump always reaches the same height, and you have less control over how long it takes to jump (physics does it):
void Update () {
float h = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
float v = Input.GetAxis("Vertical");
// move horizontally
transform.Translate(new Vector3 (h, 0, 0));
// start jump if pressing up and not in the middle of a jump
if (v > 0 && rigidbody2d.velocity.y == 0) {
rigidbody2d.velocity += new Vector2(0, 5);
}
}
The second way would be to disable the gravity, and manually move the collider up until the user releases the jump key, or you reach the peak of the jump. This allows you to control the jump better, but makes it less realistic (speed while jumping is constant). Most platformer games use this kind of jump. You’ll need to store the height in which you want the jump to stop.
Where is the gravity/jump part of the code?
– diegzumillo_1The vertical input jumps upwards. Rigidbody gravity pulls it downwards once it gets to a specific height.
– RoboticSarcasm