How to modify this Projectile class?

Started by
0 comments, last by DiegoSLTS 9 years, 8 months ago

Hi I have the following class which Updates and Draws a projectile:


public class TierOneProjectile : IProjectile
{
    private AnimatedTexture animation;
    private Vector2 screenPosition, framesPerSecond, origin;
    private float rotation, scale, depth;
    private int velocity;

    public TierOneProjectile(Vector2 _screenPosition,int _velocity,AnimatedTexture _animation)
    {
        screenPosition = _screenPosition;
        animation = _animation;
        velocity = _velocity;
    }

    public void Update(float elapsedGameTime) 
    {
        animation.UpdateFrame(elapsedGameTime);
        screenPosition.X -= velocity;

    }

    public void Draw(SpriteBatch spriteBatch) 
    {
        animation.DrawFrame(spriteBatch,screenPosition);
    }

    public Rectangle getBoundingBox() 
    {
        return new Rectangle((int)screenPosition.X, (int)screenPosition.Y, (int)animation.GetTextureWH().X, (int)animation.GetTextureWH().Y);
    }
}

Currently the projectile alway flies to the left. Little did I know when I created this class. Now I want to pass a direction to the constructor so every projectile could fly into a different direction. What would be the smartest solution for this? I do not want you to write the code for me. But maybe you could give me a hint how this could be done.

Advertisement

Change _velocity to a Vector2 and change the update function to consider velocity.x for the x component and velocity.y for the y component of the position. Also, always add the value for x, and set the direction with the sign of velocity (for the Y value you'll have to check with your current direction of Y)

And one more thing, it's a bit confusing adding a velocity to a position. I'd do something like getting a distance value (velocity.x * elapsedGameTime) and adding that value to the current position. This way you're actually using it as a speed, if one update takes longer than the previous one the projectile will move a greater distance to compensate. This means the movement doesn't depend on the frame rate of your game and you should aim for that, the projectile will move the same distance in the same amount of time in any PC or in any state of the development.

This topic is closed to new replies.

Advertisement