-1

I have the following code

public Rigidbody2D rb;
public float speed = 5f;

void FixedUpdate()
{
    if (Input.GetKeyDown("w"))
    {
        Fire();
    }
}

void Fire()
{
    rb.MovePosition(rb.position + Vector2.down * speed * Time.deltaTime);
}

but every time I play the game, the ball does not move according to the fire function, it only goes down by 1 on the y-axis.

How can I edit my code, so that the Rigidbody moves according to the Fire() function?

Alex
  • 7
  • 1

1 Answers1

1

There could be a couple things going wrong here. The first thing that stands out to me is that you're using Input.GetKeyDown instead of Input.GetKey-- GetKeyDown only returns true on the first frame that the key is pressed (so it's useful for things like shooting once per keypress), whereas GetKey returns true for the entire time that the key is down (so it's useful for things like movement). Changing that should give you the behavior that you're expecting.

Another issue is that you're doing input checking in FixedUpdate. It runs on a separate game loop from Update, and you can find more details about that here: Is it really wrong to use Input.GetKey() on FixedUpdate?

I would use Input and GetKey to store the input state in a Vector2 in the Update loop, and then use that data in FixedUpdate to do the actual movement:

public Rigidbody2D rb;
public float speed = 5f;
private Vector2 velocity = Vector2.zero;

void Update()
{
    if (Input.GetKey("w"))
    {
        velocity = Vector2.down * speed;
    }
    else {
        velocity = Vector2.zero;
    }
}

void FixedUpdate()
{
    MoveBall();
}

void MoveBall()
{
    rb.MovePosition(rb.position * velocity * Time.deltaTime);
}

This way, you also have a stronger separation between the input code and movement code, and it will be easier to handle once you start trying to implement more complexity. Good luck!