我有一个弹跳球,我试着让它弹跳一次,速度就会变快。
在我的球类类(class)中,我有一个漂浮速度;
然后我初始化了它: 公共(public)球(浮球速度) 速度 = 1f;
我有一个让我的球运动的方法,看起来像这样:
public void BallMovement()
{
if (movingUp) { ballRect.Y -= speed; }//Error
if (!movingUp) { ballRect.Y += speed; }//Error
if (movingLeft) { ballRect.X -= speed; }//Error
if (!movingLeft) { ballRect.X += speed; }//Error
if (ballPosition.Y < 85)
{
movingUp = false;
}
if (ballPosition.Y >= 480)
{
movingUp = true;
}
然后我在更新方法中添加:BallMovement();
它在我尝试使用 speed 变量之前工作,但由于这个错误而无法编译:
Cannot implicitly convert type 'float' to 'int'.An explicit conversion exists(are you missing a cast?)
请您参考如下方法:
速度需要 float 。如果你想保持速度 float ,你可以创建自己的矩形结构。你可以这样做:
public struct RectangleF
{
float w = 0;
float h = 0;
float x = 0;
float y = 0;
public float Height
{
get { return h; }
set { h = value; }
}
//put Width, X, and Y properties here
public RectangleF(float width, float height, float X, float Y)
{
w = width;
h = height;
x = X;
y = Y;
}
public bool Intersects(Rectangle refRectangle)
{
Rectangle rec = new Rectangle((int)x, (int)y, (int)w, (int)h);
if (rec.Intersects(refRectangle)) return true;
else return false;
}
}
相交检查不会绝对完美,但至少矩形的 X 和 Y 可以添加 0.5。
