To make the player slide along the wall when they run into it, you can use the concept of vector projection to remove the component of the player's velocity that is perpendicular to the wall, leaving only the component that is parallel to the wall.
Here's how you can calculate the sliding direction of the player along the wall:
-
Identify your vectors:
- Let (\mathbf{v}) be the player's intended velocity vector.
- Let (\mathbf{n}) be the normalized wall normal vector, which points outward from the wall.
-
Project the velocity onto the wall's plane:
- To get the parallel component of the velocity along the wall, you'll subtract from (\mathbf{v}) the component of the velocity in the direction of the wall normal.
-
Calculate the perpendicular component (which is the part of the velocity vector in the direction of the wall normal):
- (\mathbf{v}_{\perp} = (\mathbf{v} \cdot \mathbf{n}) \mathbf{n})
This is done using the dot product of the velocity vector (\mathbf{v}) and the normal vector (\mathbf{n}).
-
Calculate the parallel component (the desired sliding velocity):
- (\mathbf{v}{\parallel} = \mathbf{v} - \mathbf{v}{\perp})
- (\mathbf{v}_{\parallel} = \mathbf{v} - (\mathbf{v} \cdot \mathbf{n}) \mathbf{n})
Thus, the resulting velocity vector (\mathbf{v}_{\parallel}) is the projection of (\mathbf{v}) onto the plane of the wall, effectively removing the component of the velocity that would be stopped by the wall and leaving only the sliding component.
Here’s a practical example in pseudo-code:
# Assuming the player's velocity vector v and wall normal vector n
v = [vx, vy, vz] # The player's intended velocity vector
n = [nx, ny, nz] # The normalized wall normal vector
# Compute the perpendicular component of the velocity
# Dot product of v and n
dot_product = v[0] * n[0] + v[1] * n[1] + v[2] * n[2]
# Perpendicular component v_perp
v_perp = [dot_product * n[0], dot_product * n[1], dot_product * n[2]]
# Parallel component v_parallel (sliding velocity)
v_parallel = [v[0] - v_perp[0], v[1] - v_perp[1], v[2] - v_perp[2]]
# Now v_parallel is the velocity vector of the player sliding along the wall
Explanation and Additional Notes:
- Dot Product Calculation: The dot product (\mathbf{v} \cdot (\mathbf{n})) gives a scalar (i.e., a single number) that represents the extent to which (\mathbf{v}) is in the direction of (\mathbf{n}).
- Subtraction to Get Parallel Component: By subtracting the perpendicular component from the original velocity, you're left with the parallel component, which is the direction along which the player will slide.
- Assuming Vectors are Normalized: Ensure that the wall normal vector (\mathbf{n}) is indeed normalized (i.e., has a magnitude of 1). If not, normalize it before performing these calculations.
With this calculation, the player will slide along the wall in the direction of (\mathbf{v}_{\parallel}) whenever they collide with the wall.