Question

I want to have the screen follow the player, seeing that many use Matrix to make the camera do as they want, I get a little stuck. I have a main class called Game1.cs, a Player class were the movement is held and most people have the movement system in their camera function. All I want is the camera to follow the player, no zoom or rotation (at the moment).

I have the starting of the Camera class:

class Camera
{
    public Matrix Transform;
    Vector2 Position;
    Viewport viewPort;

    public Camera(Viewport viewport)
    {
        viewPort = viewport;
        Position = Vector2.Zero;
    }

    public void Update(GameTime gameTime)
    {
        Transform = Matrix.CreateTranslation(Position.X, Position.Y, 0);
    }
}

Game1.cs:

protected override void LoadContent()
{
     camera = new Camera(GraphicsDivice.Viewport);
}

Protected override void Draw(GameTime gameTime)
{
     spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.Transform);

     //Stuff Here

     spriteBatch.End();
     base.Draw(gameTime);
}

What am I missing? How do I fix this to work?

How should/do I add my Player.cs class?

Edit: 10:36 3/17/2014

I have made it follow the player by making the Matrix Transform change to a method and adding Transform() to the SpriteBatch.Begin(). I have also adding a public Player thing(Player player) to make the Position equal to the players position. But the player is stuck to the left side of the screen.

How do I make the player in the center of the screen?

The code looks like this now:

class Camera
{
    Player player;

    public Vector2 Position;
    Viewport viewPort;

    public Matrix Transform()
    {
        var translationMatrix = Matrix.CreateTranslation(new Vector3(-Position.X, 0, 0));

        return translationMatrix;
    }

    public Player thing(Player player)
    {
        Position = player.Position;

        return player;
    }

    public Camera(Viewport viewport)
    {
        viewPort = viewport;
    }

    public void Update(GameTime gameTime)
    {
    }
}
Was it helpful?

Solution

The player is stuck to the left side of the screen because you set player position as same as camera position. You need to set offset:

Vector2 offset = new Vector2(GraphicsDeviceManager.PreferredBackBufferWidth / 2, 0); //or whatever you like; new Vector2(100, 0) for an instance
Position = player.Position + offset; // plus or minus don't know just test
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top