Hi guys,
I’m developing a 2D platformer with Unity in which the main character can fly by keeping the up button pressed. However, I can’t find a way to make him fly-- rather, he simply does multiple jumps in mid-air (like in a Kirby game).
How can I fix this and make him fly?
Here’s the code I used:
[RequireComponent (typeof (Controller2D))]
public class Player : MonoBehaviour {
public float jumpHeight = 4;
public float timeToJumpApex = .4f;
public float accelerationTime = .1f;
public float moveSpeed = 6;
float gasTank = 0; // if the gasTank variable is 0 the player can't fly anymore
float gravity;
float jumpVelocity;
Vector3 velocity;
float velocityXSmoothing;
float velocityYSmoothing;
Controller2D controller;
void Start () {
controller = GetComponent <Controller2D> ();
gravity = -(2 * jumpHeight) / Mathf.Pow (timeToJumpApex, 2);
jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
}
void Update () {
// if player is touching either ground or ceiling
if (controller.collisions.above || controller.collisions.below)
velocity.y = 0;
// if player is touching only ground
if (controller.collisions.below)
gasTank = 14;
// if player presses up button the GasTank variable goes down to 0
else if (Input.GetKeyDown(KeyCode.UpArrow))
{
if (gasTank > 0)
gasTank -= 0.1f;
else
gasTank -= 0f;
}
Vector2 input = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
if (Input.GetKeyDown(KeyCode.UpArrow) && gasTank > 0){
velocity.y += jumpVelocity;
}
else
velocity.y = velocity.y;
float targetVelocityX = input.x * moveSpeed;
float targetVelocityY = input.y * moveSpeed;
velocity.x = Mathf.SmoothDamp (velocity.x, targetVelocityX, ref velocityXSmoothing, accelerationTime);
velocity.y += gravity * Time.deltaTime;
controller.Move (velocity * Time.deltaTime);
print ("Gravity: " + gravity + " jumpVelocity: " + jumpVelocity + " gasTank: " + gasTank + " velocity.y: " + velocity.y);
}
}