【发布时间】:2017-08-08 18:52:40
【问题描述】:
我正在努力解决我的玩家或敌人的碰撞矩形与关卡/墙壁之间的碰撞。
关卡是一维数组。
这画得很好:一个带有平台的屏幕和一个围绕关卡的盒子,所以玩家和敌人不应该离开竞技场。
在我的 Game_Manager 类(处理游戏、更新和碰撞)中绘制关卡、玩家和一个敌人。效果很好,但是玩家和敌人可以离开该区域,因为碰撞检测不对:
在我的 Game_Manager 类中,玩家检测到敌人并在它们碰撞时重置其位置:
if(player.PlayerCollRect.IntersectsWith(enemy.enemyCollRect))
{
player.playerPosition = playerStartPosition;
}
再次:效果很好。
但是:我似乎无法正确理解与一维数组(我的关卡)的冲突。 而且我似乎在获取关卡中每个块/瓷砖的碰撞矩形时遇到了问题 - 我的玩家可以出去,我的敌人也可以。
敌人是粉红色的,玩家是绿色的。 红色块现在不使用: See here what my level looks like and whats happening (.gif)
我试过了:
player.PlayerCollRect.IntersectsWith(enemy.EnemyCollRect)
我应该尝试与我的瓷砖碰撞吗?还是我的完整等级?以及如何?
我的 Level.cs 代码
public abstract class Level
{
protected byte[,] byteArray;
public Tile[,] tileArray;
public Rectangle levelTileColl;
public Level()
{
CreateTileArray();
tileArray = new Tile[byteArray.GetLength(0), byteArray.GetLength(1)];
CreateWorld();
}
protected abstract void CreateTileArray();
private void CreateWorld()
{
for (int r = 0; r < byteArray.GetLength(0); r++)
{
for (int c = 0; c < byteArray.GetLength(1); c++)
{
if(byteArray[r, c] == 1)
{
tileArray[r, c] = new Tile(new Point(c * 40, r * 40));
//tileArray[r, c] = new Tile(new Point(c * tile.TileWidth, r * tile.TileHeight));
}
}
}
}
public void Draw(Surface showTiles)
{
for (int r = 0; r < byteArray.GetLength(0); r++)
{
for (int c = 0; c < byteArray.GetLength(1); c++)
{
if (tileArray[r, c] != null)
tileArray[r, c].Draw(showTiles);
}
}
}
}
Level01.cs 的代码:
public class Level01 : Level
{
protected override void CreateTileArray()
{
byteArray = new Byte[,]
{
{ 1, 1, 1, 1, 1, 1, 1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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
};
}
}
Tile.cs 代码:
public class Tile
{
private Surface tileImage;
private Point tilePosition;
public Rectangle tileColl;
private int tileWidth = 40;
private int tileHeight = 40;
public int TileWidth
{
get { return tileWidth; }
set { tileWidth = value; }
}
public int TileHeight
{
get { return tileHeight; }
}
public Rectangle TileColl
{
get { return tileColl; }
set { tileColl = value; }
}
public Tile(Point position)
{
tileImage = new Surface("tile.png");
tilePosition = position;
tileColl = new Rectangle(tilePosition.X, tilePosition.Y, tileWidth, tileHeight);
}
public void Draw(Surface showTiles)
{
showTiles.Blit(tileImage, tilePosition);
}
}
-- 编辑-- 好吧,让我换一种说法: 如何检查我的玩家是否在我的关卡中与我的 tileArray 中的图块接触/碰撞/相交? 我有一个 tileArray,如果有碰撞,我想检查与任何 1 的瓷砖的碰撞(见上文)。
【问题讨论】:
标签: c# arrays sdl collision-detection rectangles