无法创建碰撞矩形

时间:2016-09-28 19:42:05

标签: c# xna

我正在为大学的编程课做一个小游戏,我在尝试创建碰撞矩形时遇到了问题。

当我尝试使用纹理的宽度和高度时。我收到一个错误,告诉我我无法从float转换为int。但是图像的像素大小不是浮点值?

以下是我在游戏对象类中的代码(有很多注释可以帮助指导事情的发展方向):

class ButtonSprite
{
    public Texture2D Art;
    public Vector2 Position;

    public ButtonSprite(Vector2 pos, Texture2D tex)
    {
        // Copy the texture "tex" into the "Art" class variable
        Art = tex;
        // Copy the vector "pos" into the "Position" class variable
        Position = pos;
    }

    public void DrawMe(SpriteBatch sb, Color col)
    {
        // use the spritebatch "sb" to draw the sprite at "Position" using the texture "Art" with the tint from "col"
        sb.Draw(Art, Position, col);
    }
}

class PlayerSprite
{
    public Texture2D Art;
    public Vector2 Position;
    public Rectangle CollisionRect;

    public PlayerSprite(Vector2 pos, Texture2D tex)
    {
        // Copy the texture "tex" into the "Art" class variable
        Art = tex;
        // Copy the vector "pos" into the "Position" class variable
        Position = pos;
        // create a new CollisionRect Rectangle using the X and Y from Position and the Width and Height from Art
        CollisionRect = new Rectangle(Position.X, Position.Y, Art.Width, Art.Height);
    }

    public void UpdateMe(ButtonState leftB, ButtonState rightB, ButtonState downB, ButtonState upB)
    {
        // if leftB is pressed
        if (leftB == ButtonState.Pressed)
        {
            // subtract 1 from the X that belongs to Position
            Position.X -= 1;
        }
        // endif

        // if rightB is pressed
        if (rightB == ButtonState.Pressed)
        {
            // add 1 to the X that belongs to Position
            Position.X += 1;
        }
        // endif

        // if downB is pressed
        if (downB == ButtonState.Pressed)
        {
            // add 1 to the Y that belongs to Position
            Position.Y += 1;
        }
        // endif

        // if upB is pressed
        if (upB == ButtonState.Pressed)
        {
            // subtract 1 from the Y that belongs to Position
            Position.Y -= 1;
        }
        // endif

        // set the X that belongs to CollisionRect to equal the integer version of the X that belongs to Position
        // set the Y that belongs to CollisionRect to equal the integer version of the Y that belongs to Position
    }

    public void DrawMe(SpriteBatch sb)
    {
        // use the spritebatch "sb" to draw the sprite at "Position" using the texture "Art" with a white tint
        sb.Draw(Art, Position, Color.White);
    }
}
}

2 个答案:

答案 0 :(得分:0)

马上,我建议你使用这个动作来计算你的碰撞。这样可以防止更多毛刺(例如穿过墙壁)。

执行此操作的一种好方法是按移动矩形的大小(暂时)膨胀目标矩形。然后,执行一行到边界框交叉点。这将为您提供一个交叉点,同时更安全地防止故障。

答案 1 :(得分:0)

在构建碰撞rect时尝​​试此行。它会转换高度和高度。 width浮动到整数。 + 1是可选的。

CollisionRect = new Rectangle(Position.X, Position.Y, (int)Art.Width + 1, (int)Art.Height + 1);
相关问题