- Home /
Problem Standing into Objects
Okay, I have been trying to work this problem out for myself for a few days now. I have done a ton of research and trial & error and am just not getting it. I know that this is kind of a common issue with people who aren't fluent in coding yet, and I have never worked with any kind of coding in my life until recently.
I have a Run & Crouch code that works really well, and I'm trying to modify it so that I can RayCast Up from my Character Controller's center while crouching and keep the character from standing up under a Collider. I think it would be better to SphereCast instead, but I have only just started looking into that approach.
I think my biggest problem is that I'm not understanding how RayCast works.
Here's my full C# code:
using UnityEngine;
using System.Collections;
public class RunAndCrouch : MonoBehaviour
{
public float walkSpeed = 5; //Default Walk Speed
public float crouchSpeed = 1.5f; //Default Crouch Speed
public float runSpeed = 10; //Default Run Speed
bool crouching;
bool running;
float standardHeight;
float crouchHeight;
CharacterMotor chMotor;
Transform tr;
float dist; //Distance To Ground
// Use this for initialization
void Start ()
{
chMotor = GetComponent<CharacterMotor> ();
tr = transform;
CharacterController ch = GetComponent<CharacterController> ();
dist = ch.height / 2; //Default Distance To Ground (Char Height)
standardHeight = ch.height;
crouchHeight = ch.height/2;
}
// Update is called once per frame
void FixedUpdate ()
{
float vScale = 1.0f;
float speed = walkSpeed;
crouching = false;
running = false;
running = Input.GetButton ("Run");
if ((running) && chMotor.grounded)
{
speed = runSpeed;
running = true;
}
else
{
running = false;
}
crouching = Input.GetButton ("Crouch");
if (crouching)
{
vScale = 0.5f;
speed = crouchSpeed;
crouching = true;
}
else
{
crouching = false;
}
if (crouching)
{
Vector3 startPos = tr.position;
float length = (standardHeight - crouchHeight);
if (Input.GetButtonUp ("Crouch"))
{
if (!Physics.Raycast (startPos, Vector3.up, length))
{
crouching = false;
}
else
{
crouching = true;
}
}
}
chMotor.movement.maxForwardSpeed = speed; //Set Max Speed
float ultScale = tr.localScale.y; //Crounch/Stand Smoothly
Vector3 tmpScale = tr.localScale;
Vector3 tmpPosition = tr.position;
tmpScale.y = Mathf.Lerp (tr.localScale.y, vScale, 5 * Time.deltaTime);
tr.localScale = tmpScale;
tmpPosition.y += dist * (tr.localScale.y - ultScale); //Fix Vertical Position
tr.position = tmpPosition;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
C# Raycast isn't working? 1 Answer
[Answered](C#) Help with dealing damage to enemy from Raycast 3 Answers
[C#] Problem with RayCast check. 1 Answer
Raycasting, LineRenderer & Layermasks 0 Answers