# Prevent rigidbody from coming off the surface

The function below is meant to make my player able to slide down a slope, while also moving along the slope if any input is detected. The problem is that, when I try to move it in the slide direction, he will exit the slide state, since he would come off the surface, which is not something I want. I want him to always stay in contact with the slope while sliding. Any ideas?

``````// called in FixedUpdate
private void HandleSlide() {
// Calculate the slide force direction and magnitude
Vector3 slideDirection = GetSlopeDirection();
float slideMagnitude = slideDirection.magnitude;

// Apply slide force
Vector3 movementInput = Player.InputHandler.MovementInput.ToIso().normalized;

// Manage velocity
float dotProduct = Vector3.Dot(Player.RB.velocity.normalized, GetSlopeDirection().normalized);

if (dotProduct < 0f) {
Player.RB.velocity = slideDirection * slideMagnitude * (Player.Data.SlideSpeed * .75f);
}
else if (dotProduct > 0f) {
Player.RB.velocity = (movementInput + slideDirection) * slideMagnitude * (Player.Data.SlideSpeed * 1.25f);
}
else {
Player.RB.velocity = (movementInput + slideDirection) * slideMagnitude * Player.Data.SlideSpeed;
}

// Rotate towards slide direction
Vector3 clampedSlideDirection = slideDirection;
clampedSlideDirection.y = 0f;
if (clampedSlideDirection != Vector3.zero)
Player.transform.rotation = Quaternion.LookRotation(clampedSlideDirection);
}
``````

Ok, I solved it, thanks to this Asteroid Base .
In case anyone else needs a similar solution, here is my code:

``````    /*
public static RaycastHit GetSlopeRaycastHit(Transform transform) {
RaycastHit slopeHit;

if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, 1.5f)) {
float angle = Vector3.Angle(Vector3.up, slopeHit.normal);

if (angle < Settings.MAX_SLOPE_ANGLE && angle != 0) {
return slopeHit;
}
}
return new RaycastHit();
}
*/
else if (dotProduct > 0f && movementInput != _oppositeDirectionInput) {
Player.RB.velocity = (movementInput + slideDirection) * slideMagnitude * (Player.Data.SlideSpeed * Player.Data.SlideSpeedMultiplier);
RaycastHit slideHit = HelperUtilities.GetSlopeRaycastHit(Player.transform);
Player.transform.position = slideHit.point + Player.transform.up * .1f;
}
``````