Skip to content

Instantly share code, notes, and snippets.

@ashblue
Last active March 16, 2023 20:08
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ashblue/5b3dafdc0a09eea729b7 to your computer and use it in GitHub Desktop.
Save ashblue/5b3dafdc0a09eea729b7 to your computer and use it in GitHub Desktop.
Unity 2D slope normalizer for walking up and downhill with corner snapping. Based upon https://www.youtube.com/watch?v=xMhgxUFKakQ
// @NOTE Must be called from FixedUpdate() to work properly
void NormalizeSlope () {
// Attempt vertical normalization
if (grounded) {
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 1f, whatIsGround);
if (hit.collider != null && Mathf.Abs(hit.normal.x) > 0.1f) {
Rigidbody2D body = GetComponent<Rigidbody2D>();
// Apply the opposite force against the slope force
// You will need to provide your own slopeFriction to stabalize movement
body.velocity = new Vector2(body.velocity.x - (hit.normal.x * slopeFriction), body.velocity.y);
//Move Player up or down to compensate for the slope below them
Vector3 pos = transform.position;
pos.y += -hit.normal.x * Mathf.Abs(body.velocity.x) * Time.deltaTime * (body.velocity.x - hit.normal.x > 0 ? 1 : -1);
transform.position = pos;
}
}
}
@pharan
Copy link

pharan commented Jul 4, 2015

If you mean this to be called from FixedUpdate, shouldn't line 15 use Time.fixedDeltaTime instead?

@SivanLiu
Copy link

thanks!The way is good!I solved the slope movement problem!

@ZandrXandr
Copy link

If you call Time.deltaTime when you're doing a FixedUpdate, it will return Time.fixedDeltaTime

@UberOmega
Copy link

Thanks for posting this!
I'm having a bit of an issue though, and I can't tell if it's Unity or if I'm misunderstanding something.

If I have the Rigidbody2D set to Extrapolate, it works well enough going up hill but still skips a bit coming down. With Interpolate it's reversed, it sticks coming down but tries to launch itself off the crest.

I also can't seem to keep it from jittering while idle on the slope, no matter how much I fiddle with the slope friction.

My slopes are all stairs, so everything is at a 90 or 45 degree angle.

Any insights would be much appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment