【发布时间】:2014-10-22 01:45:33
【问题描述】:
大家好!
让我们切入正题。 我制作了一个瓷砖引擎,可以相对于我的相机绘制我的地图(绘制的瓷砖是相机窗口中可见的瓷砖),并且我制作了一个位于相机中心的精灵(我的角色)。 每当我移动相机时,我的角色都会相应地跟随,唯一的问题是当我到达地图的边界时。我的编程方式限制了我的相机移动到边界之外,从而限制了我的角色移动到更靠近边界的位置(因为它总是在相机内居中)。
如何让我的相机摆脱邪恶地图的束缚?
附言我制作了一个picture 来说明我想要做什么。 这是我关注的guide。
这是我绘制瓷砖并放置相机的代码:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
Vector2 firstSquare = new Vector2(Camera.Location.X / Tile.TileWidth, Camera.Location.Y / Tile.TileHeight);
int firstX = (int)firstSquare.X;
int firstY = (int)firstSquare.Y;
Vector2 squareOffset = new Vector2(Camera.Location.X % Tile.TileWidth, Camera.Location.Y % Tile.TileHeight);
int offsetX = (int)squareOffset.X;
int offsetY = (int)squareOffset.Y;
for (int y = 0; y < squaresDown; y++)
{
for (int x = 0; x < squaresAcross; x++)
{
foreach (int tileID in myMap.Rows[y + firstY].Columns[x + firstX].BaseTiles)
{
spriteBatch.Draw(
Tile.TileSetTexture,
new Rectangle(
(x * Tile.TileWidth) - offsetX, (y * Tile.TileHeight) - offsetY,
Tile.TileWidth, Tile.TileHeight),
Tile.GetSourceRectangle(tileID),
Color.White);
}
}
}
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
这是我移动相机的代码:
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
IsMouseVisible = true;
KeyboardState ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.A))
{
Camera.Location.X = MathHelper.Clamp(Camera.Location.X - 2, 0, (myMap.MapWidth - squaresAcross) * Tile.TileWidth);
}
if (ks.IsKeyDown(Keys.D))
{
Camera.Location.X = MathHelper.Clamp(Camera.Location.X + 2, 0, (myMap.MapWidth - squaresAcross) * Tile.TileWidth);
}
if (ks.IsKeyDown(Keys.W))
{
Camera.Location.Y = MathHelper.Clamp(Camera.Location.Y - 2, 0, (myMap.MapHeight - squaresDown) * Tile.TileHeight);
}
if (ks.IsKeyDown(Keys.S))
{
Camera.Location.Y = MathHelper.Clamp(Camera.Location.Y + 2, 0, (myMap.MapHeight - squaresDown) * Tile.TileHeight);
}
// TODO: Add your update logic here
base.Update(gameTime);
}
【问题讨论】:
-
当相机到达边缘时,然后移动角色。或在您捕捉到按键的位置添加一些偏移量(例如:
myMap.MapWidth - squaresAcross + offset),以便相机移动得更远。