I have been trying for a while to find out how to have the player move along a slope with a 2D rigidbody. How I attempted to do it is by raycasting from the bottom of my player’s capsule collider, getting the angle of that, and multiplying that to my velocity.
private void SlopeCheck() // called from Update()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position - new Vector3(0, bc.size.y / 1.6f, 0), Vector2.down, groundCheckDistance, ground);
if (hit)
{
slopePerpendicular = Vector2.Perpendicular(hit.normal).normalized;
Debug.DrawRay(hit.point, hit.normal, Color.red);
Debug.DrawRay(hit.point, slopePerpendicular, Color.blue);
}
}
private void Movement() // called from FixedUpdate()
{
if (isGrounded && !isJumping)
{
rb.velocity = new Vector2(moveInput * speed * -slopePerpendicular.x * Time.fixedDeltaTime, moveInput * speed * -slopePerpendicular.y * Time.fixedDeltaTime);
}
else
{
rb.velocity = new Vector2(moveInput * speed * Time.fixedDeltaTime, rb.velocity.y);
}
}
I have two problems with this:
It only detects the slope from that one hit. I’d prefer it to raycast from the point of my capsule collider that collides with the ground.
If I’m moving too fast, it skips the check when transitioning slopes and I get launched up the slope. Maybe I could raycast where I will be instead of where I am?
I have no idea how to solve these problems (should I just not bother and try using custom 2D physics?), so any help would be greatly appreciated.