Search code examples
c#unity-game-enginetranslate-animation

Unity transform.translate move on x also moves z


I'm making an app that changes several Game Objects, the code works fine except that cuadro.transform.GetChild(current).transform.position = new Vector3 (0, 0, 0) moves my object 300 units on the Z axis (the same position of the parent GO)

Why is happening this?

public class ChangePaintScript : MonoBehaviour
{

    public GameObject cuadro;

    private int total;
    private int current = 0;

    private bool changing = false;

    // Use this for initialization
    void Start ( )
    {
        total = cuadro.transform.childCount;
    }

    // Update is called once per frame
    void Update ( )
    {
        if ( Input.GetKeyDown(KeyCode.Space) || changing )
        {
            changing = true;
        }

        if ( changing )
        {
            cuadro.transform.GetChild(current).Translate(new Vector3 (-1500, 0, 0) * Time.deltaTime);

            if ( Mathf.Abs(cuadro.transform.GetChild(current).transform.position.x) > 400 )
            {
                changing = false;

                cuadro.transform.GetChild(current).gameObject.SetActive(false);
                cuadro.transform.GetChild(current).transform.position = new Vector3 (0, 0, 0);
                current++;
                current %= total;
                cuadro.transform.GetChild(current).gameObject.SetActive(true);

            }
        }
    }
}

Thanks for your help!!!


Solution

  • Why is happening this?

    Because "Translate(vector)" work similar to "transform.position = tramsform position + vector". If your object have position "(0,0,300)" on starting move, than your target position will be is "(-1500 * deltatime, 0, 300)". So, when you assign "new Vector(0, 0, 0)" to the child transform, you translated child by -cuadro.transform.position value.

    So you can try replace this:

    cuadro.transform.GetChild(current).transform.position = new Vector3 (0, 0, 0);
    

    by this:

    cuadro.transform.GetChild(current).transform.localPosition= new Vector3 (0, 0, 0);
    

    or this:

    cuadro.transform.GetChild(current).transform.position= cuadro.transform.position;
    

    Hope i understand your problem rightly.