2
votes

I'm developing a 2D game with XNA game studio 4.0 and I need to make my "Hero" sprite shoot a shot sprite, which is a rectangle.

When I press left control to shoot, the shot is starting from my player. So far, it's ok, but the problem is that it never stops - its position never goes to theVoid.

Here is my code for shooting:

protected override void Update(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.LeftControl) && isShotted == false)
    {
        isShotted = true;
        shotPosition = playerPosition;            
    }
    if (isShotted == true && (shotPosition.X <= shotPosition.X+150) )
    {
        shotPosition.X += shotSpeed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
    else 
    { 
        isShotted = false;
        shotPosition = theVoid;
    }
}

Some clarification:

  • playerPosition is my "Hero" sprite position.
  • theVoid is Vector2 (700,700), when I set shotPosition = theVoid the shot dissapears.
1
shotPosition.X <= shotPosition.X + 150 is always going to be true... I think you might have meant playerPosition + 150?jonhopkins

1 Answers

4
votes

The shot never disapears because you are updating shotPosition.x every update. You are checking:

if (isShotted == true && (shotPosition.X <= shotPosition.X+150) )

And then inside that if you increment shotPosition.X:

shotPosition.X += shotSpeed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;

One option to fix this would be to check shotPosition.X against the player position - per @jonhopkins comment. If the player can move near the same speed as the shot though, they could just follow it and then the shot would never disappear, this may or may not be what you want.

Your other option is to store the position of where the shot was fired, and compare something like:

if (isShotted == true && (shotPosition.initialX+150 >= shotPosition.currentX) )

Make sure you think about this in terms of how your players and objects move around the coordinate system though. If your player is always stationary in regards to the x-axis that could simplify things compared to if they can run around the screen..