Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Last active July 18, 2023 04:40
Show Gist options
  • Save kurtdekker/5d8ae36fcd1455b8c9a5ef3913762227 to your computer and use it in GitHub Desktop.
Save kurtdekker/5d8ae36fcd1455b8c9a5ef3913762227 to your computer and use it in GitHub Desktop.
Track platforms so you can ride them around reliably.
//
// @kurtdekker
//
// Purpose: to be able to track arbitrary moving surfaces
// you want to hop on and ride around (platforms, etc.)
//
// Requires you to know if you are grounded or not.
//
// To use:
//
// Put this on any non-rotating moving platform object
// and it will track its instantaneous velocity.
// Put one of these on EVERY moving platorm.
//
// Over on your player controller:
//
// When your agent is grounded, raycast down from your agent
// and GetComponent<PlatformMotionRecorder>() on the collider you hit.
//
// In your LateUpdate(), if there was a PlatformMotionRecorder found
// above, get its .Movement property and add it to your own
// movement amount this frame.
//
// That's it. You're done.
//
// Can be used with 2D or 3D, doesn't matter.
//
// Future stretch goal:
//
// - track target rotation in the same way
// - make a GetMovement() method that accepts a "touch point"
// from the playe. Use the last rotation to project curving
// motion out appropriate to that point on the moving platform
// (eg, the far corner versus the rotational center of it).
//
using UnityEngine;
public class PlatformMotionRecorder : MonoBehaviour
{
public Vector3 Movement { get; private set; }
Vector3 lastPosition;
void Update ()
{
Vector3 position = transform.position;
Movement = position - lastPosition;
lastPosition = position;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment