- Home /
Making a cube crouch
I'm just getting started with Unity and I want to make sure I know the best practice for this kind of manipulation.
I have a cube, when the player presses crouch I want to instantly reduce it's height by half.
I am reducing the scale like so:
void Start () {
normalScale = gameObject.transform.localScale;
duckScale = new Vector3(normalScale.x, normalScale.y / 2f, normalScale.z);
}
void Update () {
if(Input.GetButtonDown("Duck"))
{
Debug.Log("Duck!");
if(!isDucking)
{
isDucking = true;
gameObject.transform.localScale = duckScale;
}
}
if(Input.GetButtonUp("Duck"))
{
if(isDucking)
{
gameObject.transform.localScale = normalScale;
}
isDucking = false;
}
}
This works fine, but the cube is then partially raised off of the ground due to it's origin being at it's center. What is the best way to alter it's y position in this case so that the bottom of the cube stays on the ground?
Thanks
$$anonymous$$athematically, it's just transform + or - normalScale / 4f.
Answer by whydoidoit · May 14, 2013 at 12:42 PM
You can put the cube inside an empty parent and align it so it's base is at the parent's coordinates, then when you scale the empty container, the cube will stay attached to the floor.
Is that best practice though? Isn't the default position at the center of an object for a reason?
Yes it's best practice. The normal position of a model is at the centre of it's feet.
Primitives are just centred is all.
You'd probably want to have centred models if you were writing a space game or a flying game, if your thing walks on the floor then you should ensure that your prefabs and models are base arranged.
Your answer
Follow this Question
Related Questions
Unity make a bird fly 0 Answers
Vector3.Lerp not working? 5 Answers
Getting Camera to Stop Following Player 1 Answer
My character won't stop crouching 1 Answer
Character Can't Move After Teleporting? 0 Answers