Professional Documents
Culture Documents
For the sake of this article I’m going to use the basic platformer I’ve implemented in previous article. I highly recommend you read it
first, especially the contents of 3rd chapter since I’m going to expand the PlayerController script.
While we can adjust the gravitation settings in Unity (“Edit -> Project Settings… -> Physics 2D -> Gravity”) I’m going to leave it
set to default values. Instead, I’m going to add certain amount of physics gravity when our character’s velocity over y-axis is greater
than 0. It may sound confusing at first but in reality it is fairly simple to understand. Depending on how long the player presses the
jump button I’m going to add multiples of gravitational force to make his character fall slower or quicker to the ground. Let’s see
We’ll start by adding two float multiplier values that will be used in our equation. I’ll also add one more boolean value that will tell us
1 using System.Collections;
using System.Collections.Generic;
2 using UnityEngine;
3
4 public class PlayerController : MonoBehaviour
5 {
6 private Rigidbody2D rigidBody2D;
7 private CircleCollider2D circleCollider2D;
[SerializeField] private LayerMask groundLayer;
8 [Range(0, 10f)] [SerializeField] private float speed = 0f;
9
10
11 float horizontal = 0f;
float lastJumpY = 0f;
12
private bool isFacingRight = true;
13 bool jump = false, jumpHeld = false;
14
15 [Range(0, 5f)] [SerializeField] private float fallLongMult = 0.85f;
16 [Range(0, 5f)] [SerializeField] private float fallShortMult = 1.55f;
17
18 void Start()
{
19 ...
20 }
21
22 void Update()
23 {
24 ...
}
25
26 void FixedUpdate()
27 {
28 ...
29 }
30
private void flipSprite()
31 {
32 ...
33 }
34
35 private bool isOnGround()
36 {
...
37 }
38 }
39
40
41
42
43
44
45
What I found out during my experiments is that the good rule of thumb is to set the gravitational multiplier for lower jumps to around
twice the value for higher jumps. In my case that’s fallShortMult = 1.55f and fallLongMult = 0.85f respectively.
Now we have to register both short and long presses coming from the player. At this point let’s remember our rule to capture the
1
2 void Update()
3 {
...
4
5 if (isOnGround() && Input.GetButtonDown("Jump")) jump = true;
6 jumpHeld = (!isOnGround() && Input.GetButton("Jump")) ? true : false;
7
8 ...
9