Skip to content

Commit 4c857bf

Browse files
committed
now handles slopes
1 parent cb649c5 commit 4c857bf

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Assets/Scripts/movement.cs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ public class movement : MonoBehaviour
2222
// jump
2323
public float jump = 1f;
2424

25+
// slope
26+
public bool isSliding = false;
27+
public float slopeLimit = 35f;
28+
private Vector3 slopeParallel;
29+
2530
// Update is called once per frame
2631
void Update()
2732
{
@@ -39,9 +44,44 @@ void Update()
3944

4045
controller.Move(move*movementSpeed*Time.deltaTime);
4146

47+
// slopes, modified from https://answers.unity.com/questions/1502223/sliding-down-a-slope-with-a-character-controller.html
48+
if (isGrounded) {
49+
RaycastHit hit;
50+
Physics.Raycast(transform.position, Vector3.down, out hit);
51+
// Saving the normal
52+
Vector3 n = hit.normal;
53+
54+
// Crossing my normal with the player's up vector (if your player rotates I guess you can just use Vector3.up to create a vector parallel to the ground
55+
Vector3 groundParallel = Vector3.Cross(transform.up, n);
56+
57+
// Crossing the vector we made before with the initial normal gives us a vector that is parallel to the slope and always pointing down
58+
slopeParallel = Vector3.Cross(groundParallel, n);
59+
Debug.DrawRay(hit.point, slopeParallel * 10, Color.green);
60+
61+
// Just the current angle we're standing on
62+
float currentSlope = Mathf.Round(Vector3.Angle(hit.normal, transform.up));
63+
64+
// If the slope is on a slope too steep and the player is Grounded the player is pushed down the slope.
65+
if (currentSlope >= slopeLimit) {
66+
isSliding = true;
67+
}
68+
// If the player is standing on a slope that isn't too steep, is grounded, as is not sliding anymore we start a function to count time
69+
else if (currentSlope < slopeLimit && isSliding) {
70+
isSliding = false;
71+
}
72+
}
73+
74+
if (isSliding) {
75+
controller.Move(slopeParallel.normalized / 2 * Time.deltaTime);
76+
}
77+
4278
// jump
4379
if (Input.GetButtonDown("Jump") && isGrounded) {
4480
velocity.y = Mathf.Sqrt(jump * -2f * gravity);
81+
if (isSliding) {
82+
// cut jump in halve
83+
velocity.y /= 2;
84+
}
4585
}
4686

4787
velocity.y += gravity*Time.deltaTime;

0 commit comments

Comments
 (0)