Last active
September 1, 2023 09:35
-
-
Save ashblue/8b5cec939ba61ce87a38 to your computer and use it in GitHub Desktop.
Unity 2D jump through platforms with fall support.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class Platform : MonoBehaviour { | |
SpriteRenderer playerGraphic; | |
Rigidbody2D playerBody; | |
BoxCollider2D playerBox; | |
CircleCollider2D playerCircle; | |
float padTop = -0.2f; // Padding applied to the top of feet platform checks (prevents player from barely standing on platform) | |
bool visible; // Is the player able to interact with the platform | |
[SerializeField] bool enableDrop; | |
void Start () { | |
GameObject player = PlayerAPI.current.gameObject; | |
playerGraphic = player.GetComponent<SpriteRenderer>(); | |
playerBody = player.GetComponent<Rigidbody2D>(); | |
playerBox = player.GetComponent<BoxCollider2D>(); | |
playerCircle = player.GetComponent<CircleCollider2D>(); | |
ToggleCollision(playerGraphic.bounds.min.y > collider2D.bounds.max.y + padTop, playerBody.velocity.y, true); | |
} | |
void FixedUpdate () { | |
if (!IsDropping()) { | |
ToggleCollision(playerGraphic.bounds.min.y > collider2D.bounds.max.y + padTop, playerBody.velocity.y); | |
} else { | |
ToggleCollision(false); | |
} | |
} | |
bool IsDropping () { | |
if (!enableDrop) return false; | |
return Input.GetAxis("Vertical") < -0.01f && Input.GetButton("Jump"); | |
} | |
void ToggleCollision (bool isEnabled) { | |
// Fake a submission to get the values toggled | |
if (isEnabled) { | |
ToggleCollision(true, -5f); | |
} else { | |
ToggleCollision(false, 0f); | |
} | |
} | |
void ToggleCollision (bool above, float velY, bool force = false) { | |
if (above == visible && !force) return; | |
// Check if falling and and above the platform | |
if (above && velY < 0.1f) { | |
ToggleColliders(false); | |
SetDepth(0f); | |
visible = true; | |
} else { | |
ToggleColliders(true); | |
SetDepth(-5f); | |
visible = false; | |
} | |
} | |
void ToggleColliders (bool ignore) { | |
Physics2D.IgnoreCollision(collider2D, playerBox, ignore); | |
Physics2D.IgnoreCollision(collider2D, playerCircle, ignore); | |
} | |
// With setting the depth you can prevent ground checks from firing false positives | |
void SetDepth (float depth) { | |
Vector3 pos = transform.position; | |
pos.z = depth; | |
transform.position = pos; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment