Hello,
I’m working on an endless scroller platformer in the style of Jetpack Joyride. It will be an endless runner, but I decided to include 3 actions: jump, double jump and glide. I followed a couple of tutorials and some of them recommended doing the movement by using
rigidbody2D.velocity
instead of transform.translate
as the latter is “teleporting” the object. I’m doing the continuous movement by doing
rigidbody2D.velocity = Vector2.right*speed;
This works fine, but if I try to add jumping, then the whole thing gets really wonky. I’m using rigidbody2D.AddForce
for the jump but I have some issues. First of all I feel like I need to apply a tremendous amount of force to barely get my cube of the ground (3000 or more compared to 250 when using transform). Even then, when the jump occurs, it seems like my cube just teleports up in the air instead of having a smooth jumping motion. Then, the cube will slowly glide in the air before falling down as if gravity was 1/10 of its value.
Another thing that I can’t explain is why the value of velocity.y
keeps changing even tho the object is moving on the ground.
I’ve tried another approach using transform.translate
that works just fine and I don’t have any of the issues I’ve mentioned. However I would really want to know why using the rigidbody physics causes those problems. Here are the 2 codes that I use for movement: currently using rigidbody2D.velocity
; transform.Translate
is commented.
`using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public float glide = 1f;
public float speed = 10f;
public float force = 250f;
private bool falling;
private int jumpsLeft = 2;
void FixedUpdate () {
falling = (rigidbody2D.velocity.y < 0);
/*
if(Input.GetKeyDown("up") && jumpsLeft > 0 && !falling){
if(jumpsLeft == 1){
rigidbody2D.AddForce(Vector2.up*force * 0.75f);
print("Double Jump");
} else {
print ("JUMP");
rigidbody2D.AddForce(Vector2.up * force);
jumpsLeft--;
falling = true;
}
}
if(Input.GetButton("Jump") && falling) {
rigidbody2D.velocity = new Vector2(0f, -glide );
print ("gliding");
gliding = true;
}
transform.Translate(speed * Time.deltaTime, 0f, 0f);
*/
if(Input.GetKeyDown("up") && jumpsLeft > 0 && !falling){
print("JUMP");
rigidbody2D.AddForce(Vector2.up*force);
jumpsLeft--;
falling = true;
}
rigidbody2D.velocity = Vector2.right*speed;
}
void OnCollisionEnter2D(Collision2D coll){
//change to use tags to prevent obstacles from resetting the jumps
print ("Grounded");
jumpsLeft = 2;
falling = false;
rigidbody2D.gravityScale = 1f;
}
}`