I made a crouching script using Java. I just thought someone might want it
//Is Crouching?
private var crouch = false;
//Create Position variables for Player
var xpos = 0;
var ypos = 0;
var zpos = 0;
//Start
function Update ()
{
//If Press "C"
if(Input.GetKeyDown("c"))
{
//If player is not crouching then..
if (crouch == false)
{
//Scaling Player down
transform.localScale += Vector3(0,-1,0);
//Player is crouching
crouch = true;
}
//If player is crouching
else
{
//Read current Position of player
xpos = (transform.position.x);
ypos = (transform.position.y + 0.49);
zpos = (transform.position.z);
//Move player to specified position
transform.position = Vector3(xpos, ypos, zpos);
//Scale player back to normal size
transform.localScale += Vector3(0,1,0);
//Set to not crouching
crouch = false;
}
}
}
For transform.localScale you can just use ( transform.localScale.y = 0.5; ) instead of += Vector3(0, -1, 0); .
The real trick with crouch code is not having your child items (weapons) crouch too/scale down. If anyone knows how to do that it would make a sweet addition. You don’t need the xpos or the zpos also. To prevent you from falling through the terrain.
I agree it would be a problem if the weapons scaled too xD
The only real issue I see is that if you have an object with a rigid body above you when you get back up, the object launches in the air xD Is there a way to not allow you to get back up if there is an object right above you?
nvm I figured it out ^^
I added a raycast as tall as my player object.
//Is Crouching?
private var crouch = false;
//Create Position variables for Player
var xpos = 0;
var ypos = 0;
var zpos = 0;
//Height of Player = Raycast Height
var heightchar = 0.0;
//Start
function Update ()
{
//If Press "C"
if(Input.GetKeyDown("c"))
{
//If player is not crouching then..
if (crouch == false)
{
//Scaling Player down
transform.localScale += Vector3(0,-1,0);
//Player is crouching
crouch = true;
}
//If player is crouching
else
{
//If Raycast off player pointing upwards with height of player IS hitting something
if (Physics.Raycast (transform.position, Vector3.up, heightchar)) {
//Read current Position of player
xpos = (transform.position.x);
ypos = (transform.position.y + 0.1);
zpos = (transform.position.z);
//Move player to specified position
transform.position = Vector3(xpos, ypos, zpos);
xpos = (transform.position.x);
ypos = (transform.position.y - 0.1);
zpos = (transform.position.z);
transform.position = Vector3(xpos, ypos, zpos);
}
//If not..
else
{
//Read current Position of player
xpos = (transform.position.x);
ypos = (transform.position.y + 0.49);
zpos = (transform.position.z);
//Move player to specified position
transform.position = Vector3(xpos, ypos, zpos);
//Scale player back to normal size
transform.localScale += Vector3(0,1,0);
//Set to not crouching
crouch = false;
}
}
}
}
Just heightchar to the desired height and your character player wont get back up from crouching if something is above him.