-
-
Save webthingee/e84a6fec6785861d8cbd173072c29068 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 hidden or 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment