Unity C# Trampoline

A simple to implement Trampoline "Trap" for 2D Unity Platformers.
 avatar
Archanine
csharp
3 years ago
2.4 kB
7
Indexable
using UnityEngine;
using System.Collections;

public class Trampoline : MonoBehaviour
{
    private SpriteRenderer spriteRender;
    private Animator anim;
    private Rigidbody2D springCollider;
    private Rigidbody2D playerBody;

    [Header("General Parameters")]
    [SerializeField] private float springForce;
    [SerializeField] private LayerMask playerLayer;
    [SerializeField] private BoxCollider2D boxCollider;

    [Header("Cooldown Parameters")]
    [SerializeField] private float cooldown;
    private float cooldownTimer = Mathf.Infinity;
    private float timeRemaining = 0;

    private void Awake()
    {
        spriteRender = GetComponent<SpriteRenderer>();
        springCollider = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    private void Update()
    {
        cooldownTimer += Time.deltaTime;
        if (cooldownTimer >= cooldown)
        {
            anim.SetBool("idle", false);
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (cooldownTimer > cooldown)
            timeRemaining = 0;
        else
            timeRemaining = cooldown - cooldownTimer;
        StartCoroutine(ActivateTrampoline(collision, timeRemaining));
    }
    private IEnumerator ActivateTrampoline(Collision2D collision, float timeRemaining)
    {
        playerBody = collision.gameObject.GetComponent<Rigidbody2D>();

        yield return new WaitForSeconds(timeRemaining);
        if (springCollider.IsTouching(playerBody.GetComponent<Collider2D>()))
        {
            if (isAbove())
            {
                anim.SetTrigger("spring");
                playerBody.velocity = new Vector2(playerBody.velocity.x, (playerBody.velocity.y + springForce));
                cooldownTimer = 0;
                anim.SetBool("idle", true);
            }
        }
    }

    private bool isAbove()
    {
        RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center,
        new Vector3((boxCollider.bounds.size.x * 0.95f), boxCollider.bounds.size.y + 0.1f, boxCollider.bounds.size.z),
        0, Vector2.up, 2, playerLayer);
        return raycastHit.collider != null;
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireCube(boxCollider.bounds.center,
        new Vector3((boxCollider.bounds.size.x * 0.95f), boxCollider.bounds.size.y + 0.1f, boxCollider.bounds.size.z));
    }
}