Skip to content

Instantly share code, notes, and snippets.

@slembcke
Last active February 12, 2018 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slembcke/ab7963f05ba1d322e6e872622ff63539 to your computer and use it in GitHub Desktop.
Save slembcke/ab7963f05ba1d322e6e872622ff63539 to your computer and use it in GitHub Desktop.
Falling down a hill.
// Gravity pulls the player down,
// but the slope of the hill pushes them in another direction.
static const float G = ...; // Acceleration due to gravity.
// First find what percentage of gravity is wasted opposing the ground normal:
float dotN = Vector3.Dot(groundNormal, -Vector3.up);
// Or simplified, just -groundNormal.y
// Subtract that from the down vector to get the percent
// That pushes the player along the ground plane.
Vector3 tangent = -Vector3.up - groundNormal*dotN;
// If you just want an uphill/downhill value, then dot with the player's forward direction.
float dotForward = Vector3.Dot(player.forward, tangent);
// Multiply that value by some constant to get their acceleration/deceleration.
Vector3 accel = ACCEL*dotForward*player.forward;
// Multiply dotN by some percent and subtract that for friction.
accel -= FRICTION*dotN*player.forward;
// Multiply their current velocity by some coefficient and subtract for drag.
accel -= DRAG*player.velocity.magnitude*player.forward;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment