I am wanting to move my Player character on a slope without any “bouncing”. I am not using a rigidbody, but the Character Controller component. I’m basically using the code from the 3d platformer playlist by Ketra Games. She has a video on slope bounce, but it doesn’t work unfortunately. I tried copying her script verbatim and got no results. Any help would be greatly appreciated because my game is dependent on this issue being fixed more than any other. Thank you!
Hi,Can you send your code?
Sure, how do I do that? I’m new to this.
Copy paste the code or send a screenshot of code and click the attached button shaped like a up arrow
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float rotationSpeed;
public float jumpSpeed;
private CharacterController characterController;
private float ySpeed;
private float originalStepOffset;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
originalStepOffset = characterController.stepOffset;
}
// Update is called once per frame
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
float magnitude = Mathf.Clamp01(movementDirection.magnitude) * speed;
movementDirection.Normalize();
ySpeed += Physics.gravity.y * Time.deltaTime;
if (characterController.isGrounded)
{
characterController.stepOffset = originalStepOffset;
ySpeed = -0.5f;
if (Input.GetButtonDown("Jump"))
{
ySpeed = jumpSpeed;
}
}
else
{
characterController.stepOffset = 0;
}
Vector3 velocity = movementDirection * magnitude;
velocity = AdjustVelocityToSlope(velocity);
velocity.y += ySpeed;
characterController.Move(velocity * Time.deltaTime);
if (movementDirection != Vector3.zero)
{
Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
private Vector3 AdjustVelocityToSlope(Vector3 velocity)
{
var ray = new Ray(transform.position, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hitInfo, 0.2f))
{
var slopeRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
var adjustedVelocity = slopeRotation * velocity;
if (adjustedVelocity.y < 0)
{
return adjustedVelocity;
}
}
return velocity;
}
}
Check if the value of adjustvelocity.y is it returning value<0
I suspect the ray cast distance isn’t far enough in AdjustVelocityToSlope. Instead of 0.2f try 1.2f.
Thank you both! 1.2f wasn’t enough but 5f was!