1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
namespace CompositeSprite
{
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;
    using Microsoft.Xna.Framework.Input;

    public class CompositeSpriteGame : Game
    {
        public CompositeSpriteGame()
        {
            new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            Texture2D tankTexture = Content.Load<Texture2D>("tank");
            Texture2D turretTexture = Content.Load<Texture2D>("turret");
            _tank = new Sprite(tankTexture)
            {
                Position = new Vector2(GraphicsDevice.Viewport.Width/2f, GraphicsDevice.Viewport.Height/2f), 
                Scale = 2f,
            };
            _tankTurret = new Sprite(turretTexture)
            {
                Position = new Vector2(37, 50), 
                Origin = new Vector2(23, 52),
            };
            _tank.Children.Add(_tankTurret);
        }

        protected override void Update(GameTime gameTime)
        {
            float elapsed = (float) gameTime.ElapsedGameTime.TotalSeconds;
            KeyboardState keyboard = Keyboard.GetState();
            if (keyboard.IsKeyDown(Keys.A)) _tankTurret.Rotation -= MathHelper.ToRadians(360) * elapsed;
            if (keyboard.IsKeyDown(Keys.D)) _tankTurret.Rotation += MathHelper.ToRadians(360) * elapsed;
            if (keyboard.IsKeyDown(Keys.Left)) _tank.Rotation -= MathHelper.ToRadians(90) * elapsed;
            if (keyboard.IsKeyDown(Keys.Right)) _tank.Rotation += MathHelper.ToRadians(90) * elapsed;
            if (keyboard.IsKeyDown(Keys.Up)) _tank.Position += Vector2.Transform(-Vector2.UnitY, Matrix.CreateRotationZ(_tank.Rotation)) * 200f * elapsed;
            if (keyboard.IsKeyDown(Keys.Down)) _tank.Position -= Vector2.Transform(-Vector2.UnitY, Matrix.CreateRotationZ(_tank.Rotation)) * 200f * elapsed;
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            _spriteBatch.Begin();
            _tank.Draw(_spriteBatch);
            _spriteBatch.End();
            base.Draw(gameTime);
        }

        private SpriteBatch _spriteBatch;
        private Sprite _tank;
        private Sprite _tankTurret;
    }
}