C# 在动画游戏中防止碰撞
我一直在尝试编程一种防止我的角色触碰墙壁的方法,这样他就无法穿过墙壁,但我找不到一种正确的方法,就像你在这段视频(我录制的)中看到的那样。对不起,麦克风的质量太差了:。我还说了防止碰撞,但它会检测到碰撞并停止,但你可以通过 冲突代码为:C# 在动画游戏中防止碰撞,c#,collision-detection,collision,C#,Collision Detection,Collision,我一直在尝试编程一种防止我的角色触碰墙壁的方法,这样他就无法穿过墙壁,但我找不到一种正确的方法,就像你在这段视频(我录制的)中看到的那样。对不起,麦克风的质量太差了:。我还说了防止碰撞,但它会检测到碰撞并停止,但你可以通过 冲突代码为: foreach (PictureBox pbMur in pbListeMurs) { if (pbCharacterCat.Bounds.IntersectsWith(pbMur.Bounds)) { if (pbCharact
foreach (PictureBox pbMur in pbListeMurs)
{
if (pbCharacterCat.Bounds.IntersectsWith(pbMur.Bounds))
{
if (pbCharacterCat.Right > pbMur.Left)
{
bWalkRight = false;
bIdle = true;
}
}
}
谢谢D我不确定您是如何使用
bIdle
和walkRight
的,但是这些类型的布尔标志很容易出错,它会使您的整个代码变得一团糟,因为您通常会试图堵塞漏洞,并在过程中产生新的漏洞
首先,你为什么需要它们?这还不够吗
var newPotentialCharacterBounds =
GetNewBounds(pbCharacterCat.Bounds, movementDirection);
var collidedWalls = pbListeMurs.Where(wall =>
wall.Bounds.IntersectsWith(newPotentialCharacterBounds));
if (!collidedWall.Any())
{
pbCharacterCat.Bounds = newPotentialCharacterBounds
}
//else do nothing
这是怎么回事?好吧,前提是你的角色不能从一个无效的位置开始,如果它永远不被允许到达一个无效的位置,那么你永远不需要撤销移动或重置位置
我建议您创建一个描述所有可能方向的枚举:
enum Direction { Up, Down, Left, Right };
当给出相应的方向命令时,获取角色的潜在新位置(newPotentialCharacterBounds
和GetNewBounds
)。如果该位置与任何物体发生碰撞,则什么也不做,如果不发生碰撞,则移动
更新:伪代码如下:
//event handler for move right fires, and calls:
TryMove(pbCharacterCat, Direction.Right)
//event handler for move left fires and calls:
TryMove(pbCharacterCat, Direction.Left)
//etc.
private static Rectangle GetNewBounds(
Rectangle current, Direction direction)
{
switch (direction)
{
case Direction.Right:
{
var newBounds = current;
newBounds.Offset(horizontalDelta, 0);
return newBounds;
}
case Direction.Left:
{
var newBounds = current;
newBounds.Offset(-horizontalDelta, 0);
return newBounds;
}
//etc.
}
//uses System.Linq
private bool TryMove(Control ctrl, Direction direction)
{
var newBounds =
GetNewBounds(ctrl.Bounds, direction);
var collidedWalls = pbListeMurs.Where(wall =>
wall.Bounds.IntersectsWith(newBounds));
if (!collidedWall.Any())
{
ctrl.Bounds = newBounds;
return true;
}
//Can't move in that direction
Debug.Assert(collidedWall.Single); //sanity check
return false;
}
因为
TryMove
返回移动是否成功,现在您可以利用该信息;例如,不同的音效等。您当前的代码是…?所以您想让我们去其他地方,观看游戏视频,然后想象代码可能是什么样子,然后设计碰撞代码?请阅读并使用@InBetween Yo,对不起,我忘了!已经添加了!您正在检查猫是否在墙内,但如果不纠正这种情况,则必须将猫拉出墙外:D@Gusman我如何做到这一点而不破坏动画。因为把猫传送回来会很难看。我有点明白你在给我看什么,但不太明白如何使用它。