好的,所以在我正在开发的XNA 4.0游戏中我遇到了这个问题,其中一个方法是获取错误'并非所有代码路径都返回一个值'而且这一直让我感到疯狂过了几个小时。
private Rectangle HandleCollision(Rectangle bounds, TileCollision collision, Rectangle tileBounds)
{
Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
if (depth != Vector2.Zero)
{
float absDepthX = Math.Abs(depth.X);
float absDepthY = Math.Abs(depth.Y);
// Resolve the collision along the shallow axis.
if (absDepthY < absDepthX || collision == TileCollision.Platform)
{
// If we crossed the top of a tile, we are on the ground.
// also ladder
if (previousBottom <= tileBounds.Top)
{
if (collision == TileCollision.Ladder)
{
if (!isClimbing && !isJumping)
{
//walking over a ladder
isOnGround = true;
}
}
else
{
isOnGround = true;
isClimbing = false;
isJumping = false;
}
}
// Ignore platforms, unless we are on the ground.
if (collision == TileCollision.Impassable || IsOnGround)
{
// Resolve the collision along the Y axis.
Position = new Vector2(Position.X, Position.Y + depth.Y);
// Perform further collisions with the new bounds.
bounds = BoundingRectangle;
}
}
else if (collision == TileCollision.Impassable) // Ignore platforms.
{
// Resolve the collision along the X axis.
Position = new Vector2(Position.X + depth.X, Position.Y);
// Perform further collisions with the new bounds.
bounds = BoundingRectangle;
}
else if (collision == TileCollision.Ladder && !isClimbing)
{
//stops colliding with ladder if player walks past or drops off ladder
Position = new Vector2(Position.X, Position.Y);
//perform collisions with new bounds
bounds = BoundingRectangle;
}
return bounds;
}
}
理解这个错误的任何帮助都将不胜感激,谢谢。
答案 0 :(得分:3)
您的问题就在这里。
if (depth != Vector2.Zero)
如果此计算结果为false,则不返回任何内容。
答案 1 :(得分:0)
将return bounds;
语句移到if
语句之外。如果if
语句解析为false,则永远不会命中返回。
答案 2 :(得分:0)
如果深度等于Vector2.Zero,则不返回任何内容。因此,并非所有代码路径都返回一个值。
答案 3 :(得分:0)
如果您的depth != Vector2.Zero
返回false
if ( depth != Vector2.Zero )
条件?
此时您的方法不返回任何内容。您必须在此循环之外返回值。
答案 4 :(得分:0)
return语句嵌套在条件内。因此,如果(depth == Vector2.Zero),该方法将不返回值。
答案 5 :(得分:0)
这是因为如果你首先IF
会返回false
,那么错误就是Not all code paths return a value
。您应该考虑添加一个返回值,或者可能是该案例的例外
答案 6 :(得分:0)
您需要将最终返回值移至if:
之外private Rectangle HandleCollision(Rectangle bounds, TileCollision collision, Rectangle tileBounds)
{
if(depth != Vector2.Zero)
{
}
return bounds;
}
你是这样的:
private Rectangle HandleCollision(Rectangle bounds, TileCollision collision, Rectangle tileBounds)
{
if(depth != Vector2.Zero)
{
return bounds;
}
}
这意味着,如果depth == Vector2.Zero
没有返回任何内容,那么您将收到您所看到的错误。