I create the projectile when I press the space bar like this
if (keyboard.IsKeyDown(Keys.Space) && shoot)
{
shoot = false;
this.fire.Play(.2f, .9f, 0);
lazerX = (float)(spritePosX);
lazerY = (float)(spritePosY);
Projectile projectile = new Projectile(heroLazer, "heroLazer",
lazerX, lazerY, rotationAngle);
Game1.AddProjectile(projectile);
}
then in the Projectiles class the new instance is created like this.
public Projectile(Texture2D lazerSprite, string spriteName,
float posx, float posy, float heading)
{
projectileSprite = lazerSprite;
type = spriteName;
spriteRotOrigin = new Vector2(projectileSprite.Width / 2, projectileSprite.Height / 2);
spriteHeading = heading;
spritePosX = posx; // the x position of the lazer
spritePosY = posy; // the y position of the lazer
spritePos = new Vector2(spritePosX, spritePosY);
drawRectangle = new Rectangle((int)spritePosX, (int)spritePosY,
projectileSprite.Width / 2, projectileSprite.Height / 2);
}
updated like this
public void update(GameTime gameTime, KeyboardState keyboard)
{
//projectile active or not?
if (active == true)
{
projectileAge += gameTime.ElapsedGameTime.Milliseconds;
spritePosX += (float)(Math.Sin(spriteHeading) *
gameTime.ElapsedGameTime.TotalMilliseconds) * ProjectileMoveAmount;
spritePosY -= (float)(Math.Cos(spriteHeading) *
gameTime.ElapsedGameTime.TotalMilliseconds) * ProjectileMoveAmount;
spritePos = new Vector2(spritePosX, spritePosY);
}
if (projectileAge > projectileLife)
{
active = false;
}
}
and drawn on screen like this
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(projectileSprite, spritePos, null,
Color.FromNonPremultiplied(255, 255, 255, 255), spriteHeading,
spriteRotOrigin, 1.0f, SpriteEffects.None, 0f);
}
The above code works well EXCEPT that the projectile fires from the CENTER OF THE SPACESHIP.
I can't capture an image which shows the projectile shooting from the center of the spaceship, but it does. What is wrong with my code? My trigonometry is rather weak so please be gentle and give some details.
I thank all those who set me on the way. The following simple lines of code solved the problem perfectly.
if (keyboard.IsKeyDown(Keys.Space) && shoot)
{
shoot = false;
//is.fireInst.Play();
this.fire.Play(.2f, .9f, 0);
float newRotAngle = Game1.DegreesToRadians(rotationAngle);
// the new code
lazerX = spritePosX + (float)Math.Sin(rotationAngle) * HeroSprite.Width / 2;
lazerY = spritePosY - (float)Math.Cos(rotationAngle) * HeroSprite.Height/2;
Projectile projectile = new Projectile(heroLazer, "heroLazer",
lazerX, lazerY, rotationAngle);
Game1.AddProjectile(projectile);
}