- Home /
Question by
MetalMario64 · Sep 22, 2014 at 09:03 PM ·
jumping
Jumping By Set Amount Instead of By Speed
I want to make my character jump by a set amount instead of by a velocity. The way it is now, the double jump when activated at the beginning of the first jump sends the character flying really high, but if used at the bottom of the first jump, does almost nothing at all. I want to make them jump by set amounts instead so that they jump the same way no matter when or where the jump takes place.
Here is all the code related to jumping that I have. What could I do to fix this? Thanks.
//Ground Check Variables
bool onGround = false;
public Transform checkGround;
float groundRadius = 0.2f;
public LayerMask Ground;
public float jumpSpeed = 225; //Jump Speed
bool doubleJump = false;
bool tripleJump = false;
void Update ()
{
//Jump Control
if ((onGround || !doubleJump || !tripleJump) && Input.GetKeyDown (KeyCode.Space))
{
anim.SetBool ("Ground", false);
rigidbody2D.AddForce (new Vector2(0, jumpSpeed));
if(!doubleJump && !onGround && !tripleJump)
{
jumpSpeed = 200;
doubleJump = true;
}
if(doubleJump && !onGround && !tripleJump)
{
jumpSpeed = 100;
tripleJump = true;
}
jumpSpeed = 225; //Resets the first jumps' jumpSpeed.
}
}
Comment
Answer by mouurusai · Sep 23, 2014 at 02:58 AM
Hi it's very interesting question. using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class JumpTest : MonoBehaviour
{
public float jumpHeight = 3;
public int jumpCountLimit = 3;
private int _jumpCount;
public float prevY;
private float _totalY;
private float _startY;
void Update ()
{
Vector3 rbVel = rigidbody.velocity;
rbVel.z = Input.GetAxis("Horizontal")*5;
rigidbody.velocity = Vector3.MoveTowards(rigidbody.velocity, rbVel, (_jumpCount == 0 ? 20 : 8)*Time.deltaTime);
float deltaY = prevY - transform.position.y;
if (deltaY > 0)
_totalY += deltaY;
prevY = transform.position.y;
if (Input.GetKeyDown(KeyCode.Space))
{
if(_jumpCount<jumpCountLimit)
Jump();
}
}
void Jump()
{
if(_jumpCount==0)
{
_startY = transform.position.y;
_totalY = 0;
}
++_jumpCount;
float g = Physics.gravity.y;
float h = jumpHeight * _jumpCount - _totalY - (transform.position.y-_startY);
float v = Mathf.Sqrt(-2*g*h);
Vector3 newVel = rigidbody.velocity;
newVel.y = v;
rigidbody.velocity = newVel;
}
void OnCollisionEnter()
{
_jumpCount = 0;
}
}