# Moving Smoothly Up and Down a Slope in a Platformer

To make a character move smoothly up and down a slope in a platformer,

start by figuring out the angle, θ of the slope, which is equal to the angle between the normal to the slope and a vector pointing up.

## Obtain the Normal to the Slope

Knowing this, obtain the normal to the slope. In Unity, this can be done by casting a ray of a set length from the feet of the character in the direction it is moving, then get the normal vector from the raycast hit data.

Then figure out the angle between two vectors, the normal vector to the slope and a vector pointing up. This angle is the angle of the slope, θ.

## Apply Some Trigonometry to the Movement Vector

Recall some trigonometry, know that,

Suppose the character is moving, it would be moving at a speed in a direction, at a *velocity*, which can be represented as a vector.

On a flat platform, if it is moving right at a speed, its velocity vector is most likely an arrow on a line pointing right, where its x component is of a certain magnitude equal to the moving speed, and its y component of 0. However, if it is moving along a slope, both the x and y components are certainly not 0.

Also, consider while it is moving on a slope, it is moving both horizontally and vertically at the same time along two axes. Now all that's left is to figure out what the x and y components of the velocity vector ought to be when the character is moving along the slope.

## Making the Character Move at the Correct Velocity When it is Moving Along a Slope

The character was moving at a velocity before hitting the slope. After it hits the slope, it continues on moving along at a velocity, but this time taking into consideration that it is moving along a slope, elevated at an angle, θ.

Derived using trigonometry,

`x = x component of the velocity when it hits the slope * cos θ`

`y = horizontal speed when it hits the slope * sin θ`

Note that for the x component, the direction is taken into account, hence it is a velocity. For the y component, only the magnitude, hence it is a speed.

This is because when moving left, the horizontal component of the velocity is most likely negative if it is positive when moving right. If this is not taken into account, the character will only be able to move in the same direction.

When solving for the y component, we consider a slope to be at a scalar height, elevated at an angle that starts from the horizontal plane of the platform it is on. If we take the direction of the horizontal velocity into account here, the character will not be able to move on a slope when it is moving left.

Finally make a vector out of these components and assign this vector to be the velocity of the character whenever you want it to move smoothly along the slope.