1
\$\begingroup\$

So im fairly new to coding and don't know much and so I decide to improve this line of code I had before, by finding something online and now my object is constantly moving and won't stop unless it hits a wall and I don't know how to fix it. Here is the code:

public float moveX = 0f;
public float moveY = 0f;
private bool gameStarted = false;

void Update()
{
 if (gameStarted)
 {
  float moveSpeed = 6f;
  if(Input.GetKey(KeyCode.W)) {moveY = +1f;} 
  if(Input.GetKey(KeyCode.UpArrow)) {moveY = +1f;}
  if(Input.GetKey(KeyCode.A)) {moveX = -1f;}
  if(Input.GetKey(KeyCode.LeftArrow)) {moveX = -1;}
  if(Input.GetKey(KeyCode.S)) {moveY = -1f;}
  if(Input.GetKey(KeyCode.DownArrow)) {moveY = -1f;}
  if(Input.GetKey(KeyCode.D)) {moveX = +1f;}
  if(Input.GetKey(KeyCode.RightArrow))moveX = +1f;
  Vector3 moveDir = new Vector3(moveX, moveY).normalized;
  transform.position += moveDir * moveSpeed * Time.deltaTime; 
}
    
 if (Input.GetKeyDown(KeyCode.Space))
 {
 GameStart();
 }
}

void GameStart()
{
 gameStarted = true;
}  
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

The problem here is that moveY (and probably moveX as well, but its declaration is missing from what you posted) is declared on the level of the class. Which means that it retains the value after the Update() method is over. That means that when moveY is +1f at the end of one update, it will still be +1f at the start of the next. And when nothing changes it, it will still be +1f when you use it to calculate the new movement vector.

How do we fix this?

You could move the declaration of the variables inside the Update() function, so it only exists within that function and gets reset back to 0 whenever it is executed.

void Update()
    {
     if (gameStarted)
     {
      float moveSpeed = 6f;
      float moveY = 0f;
      float moveX = 0f;
      if(Input.  /* ... */
  

Or you could leave the declarations where they are and reset them back to 0 before you check for which buttons are pressed. That way the variables remain visible for other methods of that class:

void Update()
    {
     if (gameStarted)
     {
      float moveSpeed = 6f;
      moveY = 0f;
      moveX = 0f;
      if(Input.  /* ... */
\$\endgroup\$
1
  • 1
    \$\begingroup\$ And by the way: This input handling code would look a lot cleaner if you used Input.GetAxisRaw instead of checking for individual keys. Which would also make this problem go away as a side-effect. But I didn't want to propose this as an answer, because I think it is more important for you to understand why this problem occurs rather than just get a drop-in solution that doesn't teach you what your actual mistake was. \$\endgroup\$
    – Philipp
    Commented Jun 29 at 9:01

You must log in to answer this question.

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