I use the following code to create Parallax Scrolling:
http://www.david-gouveia.com/portfolio/2d-camera-with-parallax-scrolling-in-xna/
Parallax Scrolling is working but I don't know how to focus the camera on the player. If the player moves, then the camera doesn't follow the player. The player leaves the screen when I'm moving it.
I use the following code(as described in the tutorial), but it's not working:
// Updates my camera to lock on the character
_camera.LookAt(player.Playerposition);
What can I do so that the player is always in the center of the screen/camera?
My player class:
public class Player
{
Texture2D Playertex;
public Vector2 Playerposition = new Vector2(400, 240);
private Game1 game1;
public Player(Game1 game)
{
game1 = game;
}
public void Load(ContentManager content)
{
Playertex = content.Load<Texture2D>("8bitmario");
TouchPanel.EnabledGestures = GestureType.HorizontalDrag;
}
public void Update(GameTime gameTime)
{
while (TouchPanel.IsGestureAvailable)
{
GestureSample gs = TouchPanel.ReadGesture();
switch (gs.GestureType)
{
case GestureType.HorizontalDrag:
Playerposition.X += 3f;
break;
}
}
}
public void Render(SpriteBatch batch)
{
batch.Draw(Playertex, new Vector2(Playerposition.X - Playertex.Width / 2, Playerposition.Y - Playertex.Height / 2), Color.White);
}
}
In Game1, I update the player and camera class:
protected override void Update(GameTime gameTime)
{
// Updates my character's position
player.Update(gameTime);
// Updates my camera to lock on the character
_camera.LookAt(player.Playerposition);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
foreach (Layer layer in _layers)
layer.Draw(spriteBatch);
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, _camera.GetViewMatrix(new Vector2(0.0f, 0.0f)));
player.Render(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}