0
\$\begingroup\$

I have a simple 2d scene, where I'm trying to have a sprite at x = -8 which I can move up and down. The problem is, when playing the scene, the sprite "jumps" by itself to the middle, x = 0, for no apparent reason. It then only goes back to x = -8 when there is input to move it. How do I get it to stop "jumping" to the middle at the start of every play?

using UnityEngine;
public class player1 : MonoBehaviour
{
     Vector2 targetPos;
     public float speed;
     public float step;
     void Start()
     {
         transform.position = new Vector2(-8,0);
     }
     void Update()
     {
         if (Input.GetKey("w") && transform.position.y < 3.8)
         {
             targetPos = new Vector2(-8, transform.position.y + step);
         }
         if (Input.GetKey("s") && transform.position.y > -3.8)
         {
             targetPos = new Vector2(-8, transform.position.y - step);
         }
         transform.position = Vector2.MoveTowards(transform.position, targetPos, speed);
     }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Hint: what value does targetPos have on the first frame, before you've given any input? \$\endgroup\$ – DMGregory Jun 10 '20 at 18:49
  • \$\begingroup\$ Thanks! This just shows how much of a newbie I am! Guess I'll be more careful from now on! \$\endgroup\$ – Aathish Bhagwandhin Jun 11 '20 at 16:40
1
\$\begingroup\$

targetPos is initialised by default to (0,0), which causes the sprite to move to the centre. Add to the start() method targetPos = new Vector2(-8,0); which correctly initialises it to the desired position.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.