Hello.
How can I fix bouncing on ramp, so character sticks to ground?
assuredchillyantelope
Code:
using System;
using System.Collections;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
[SerializeField] private string horizontalInputName;
[SerializeField] private string verticalInputName;
[SerializeField] private float movementSpeed;
private CharacterController charController;
[SerializeField] private AnimationCurve jumpFallOff;
[SerializeField] private float jumpMultiplier;
[SerializeField] private KeyCode jumpKey;
private Boolean isJumping;
public GameObject platform;
private void Awake() {
charController = GetComponent<CharacterController>();
}
private void Update() {
PlayerMovement();
}
private void PlayerMovement() {
float vertInput = Input.GetAxis(verticalInputName);
float horizInput = Input.GetAxis(horizontalInputName);
Vector3 forwardMovement = transform.forward * vertInput;
Vector3 rightMovement = transform.right * horizInput;
Vector3 moveDir = Vector3.zero;
RaycastHit hit;
if (!isJumping && Physics.Raycast(transform.position, Vector3.down, out hit)) {
moveDir = SlopeAngle(forwardMovement + rightMovement, hit.normal);
Debug.DrawLine(hit.point, moveDir, Color.red, 3f);
}
moveDir.Normalize();
charController.SimpleMove(moveDir * movementSpeed);
JumpInput();
}
private Vector3 SlopeAngle(Vector3 vector, Vector3 normal) {
return Vector3.ProjectOnPlane(vector, normal);
}
private void JumpInput() {
if(Input.GetKeyDown(jumpKey) && !isJumping && charController.isGrounded) {
isJumping = true;
StartCoroutine(JumpEvent());
}
}
private IEnumerator JumpEvent() {
float timeInAir = 0;
do {
float jumpForce = jumpFallOff.Evaluate(timeInAir);
charController.Move(Vector3.up * jumpForce * jumpMultiplier * Time.deltaTime);
timeInAir += Time.deltaTime;
yield return null;
} while (!charController.isGrounded && charController.collisionFlags != CollisionFlags.Above);
isJumping = false;
}
}