0
\$\begingroup\$

In Unity, I have this problem where the Game Object this script is attached to jumps to Z position 0 as soon as the game runs. In the Editor, I have the Game Object set as Z position -50. I want startPos to read this position (-50) and use it when newPos is updated.

Why does startPos get updated immediately to 0?

using UnityEngine;

public class MoveOutScript : MonoBehaviour {

    public float speed = 10f;
    float startPos;
    Vector3 newPos;
    float changePerSecond2;

    public void Start()
    {    
        startPos = transform.position.z;
        changePerSecond = speed * Time.deltaTime;
    }

    public void Update()
    {    
        #region Move sprite away steadily

        newPos.z += changePerSecond;
        newPos.z = Mathf.Clamp(newPos.z, startPos, 15f);
        transform.localPosition = newPos;

        #endregion
    }
}
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

It is probably because you are updating the local position, even though you get your start position from the absolute position. If its parent is not at the origin but instead at (0, 0, 50), a local position of (0, 0, -50) would put it right at the origin.

Perhaps having transform.position = newPos instead would fix it.

\$\endgroup\$
1
  • \$\begingroup\$ Nice one! That probably is it. I was recycling some code and missed that. I'll give it a try tomorrow and get back to you. \$\endgroup\$
    – Profplum
    Commented Sep 21, 2017 at 19:01
0
\$\begingroup\$

It was as simple as me not declaring newPos to equal startPos in the Start() method. newPos was defaulting to 0, which is why it always started from that position. Now, it starts at startPos.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .