Question by
ksewo · Sep 14, 2019 at 08:26 PM ·
collisionphysicscharactercontrollercharacter movementphysics.raycast
CharacterController bounce on ramp instead of smooth walk
Hello. How can I fix bouncing on ramp, so character sticks to ground?
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;
}
}
Comment
Your answer
Follow this Question
Related Questions
Recreating 'skin width' functionality on a rigidbody? 0 Answers
2D Character Controller that only allows sliding against walls 0 Answers
I'm having issues with collision and Physics 1 Answer
Problem with character controller movement and gravity 0 Answers
charactercontroller car acceleration and deceleration 0 Answers