- Home /
Question by
Matt1928 · Feb 07, 2020 at 06:57 PM ·
charactercontrollercharacter controllercharacter movement
How can I slide with a character controller
This is what I have so far.
public float SlopeForce;
public float slopeForceRayLength;
public CharacterController controller;
public Transform groundCheck;
public float groundDistance = 0.3f;
public LayerMask groundMask;
public bool Jumping;
Vector3 velocity;
bool isGrounded;
void Start()
{
}
// Update is called once per frame
void Update()
{
Jump();
physics();
Movement();
Crouch();
}
public void Jump()
{
if (Input.GetButtonDown("Jump") && isGrounded)
{
Jumping = true;
controller.slopeLimit = 90f;
velocity.y = Mathf.Sqrt(JumpHeight * -2f * gravity);
controller.slopeLimit = 45f;
Jumping = false;
}
}
public void physics()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
public void Movement()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if((x != 0 || z != 0) && OnSlope())
{
controller.Move(Vector3.down * controller.height / 2 * SlopeForce * Time.deltaTime);
}
}
public void Crouch()
{
if (Input.GetKeyUp("c"))
{
transform.localScale = new Vector3(x:1, y:1, z:1);
}
if (Input.GetKeyDown("c"))
{
transform.localScale = new Vector3(x:1, y:CrouchHeight, z:1);
}
}
public bool OnSlope()
{
if (Jumping)
return false;
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, controller.height/2 * slopeForceRayLength))
if (hit.normal != Vector3.up)
return true;
return false;
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612222925im_/https://answers.unity.com/themes/thub/images/avi.jpg)