- Home /
Crouching script
I'm making a first person game and I need to implement crouching. I've got the moving and looking down, I just need a crouch script. But I have no clue how to make it. Where do I even put it? A seperate script, the moving script, the looking script? Idk, but this is my moving script.`
public class ControllingScript : MonoBehaviour {
public float walkSpeed = 10f;
// Use this for initialization
void Start ()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update ()
{
float translation = Input.GetAxis ("Vertical") * walkSpeed;
float straffe = Input.GetAxis ("Horizontal") * walkSpeed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translation);
if (Input.GetButtonDown("escape"))
Cursor.lockState = CursorLockMode.None;
}
`
Got any ideas?
Answer by Koyemsi · May 04, 2018 at 03:29 PM
Hi. I assume your player is done the classical way (one camera + capsule collider), like in the Standard Assets ? Maybe you could reduce the vertical size of the capsule to its half, or something like that ? I think I would put the crouching code in the moving script.
I tried, but i don't know if I did it incorrectly or It doesn't work.
Try something like this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControllingScript : $$anonymous$$onoBehaviour {
public float walkSpeed = 10f;
private CapsuleCollider capsuleColl;
private float capsuleHeight;
private Vector3 capsuleCenter;
void Start () {
Cursor.lockState = CursorLock$$anonymous$$ode.Locked;
capsuleColl = GetComponentInChildren<CapsuleCollider> ();
capsuleHeight = capsuleColl.height;
capsuleCenter = capsuleColl.center;
}
void Update () {
float translation = Input.GetAxis ("Vertical") * walkSpeed;
float straffe = Input.GetAxis ("Horizontal") * walkSpeed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate (straffe, 0, translation);
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.LeftControl))
Crouching (true);
if (Input.Get$$anonymous$$eyUp ($$anonymous$$eyCode.LeftControl))
Crouching (false);
}
void Crouching (bool myBool) {
if (myBool) {
capsuleColl.height = capsuleHeight / 2;
capsuleColl.center = capsuleCenter;
} else {
capsuleColl.height = capsuleHeight;
capsuleColl.center = capsuleCenter;
}
}
}
Your player must have a CapsuleCollider, of course.
Your answer