Last active
March 16, 2023 20:08
-
-
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
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
// @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; | |
} | |
} | |
} |
thanks!The way is good!I solved the slope movement problem!
If you call Time.deltaTime when you're doing a FixedUpdate, it will return Time.fixedDeltaTime
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
If you mean this to be called from FixedUpdate, shouldn't line 15 use Time.fixedDeltaTime instead?