无法在XNA中隐式转换类型
我有一个弹跳球,我试图这样做,当它反弹一次,速度变得更高。
在我的球课上,我有一个float speed;
我初始化它: public ball(float speed) speed = 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 = 480) { movingUp = true; }
然后我在update方法中添加它: BallMovement();
它在我尝试使用速度变量之前工作,因为这个错误它不会编译:
无法将类型’float’隐式转换为’int’。存在显式转换(您是否错过了转换?)
速度需要浮动。 如果要将速度保持为浮点数,可以创建自己的矩形结构。 你可以这样做:
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。 HTH
你试图从一个int中减去一个浮点值(例如:1.223488)(例如:12); 你不能这样做。 将两个值转换(转换)为浮点数,或将两个值转换(转换)为整数:
if (movingUp) { ballRect.Y -= (int)speed; }//Error
错误基本上是说“我们不能自动为你转换(隐式),但你可以自己转换(显式)。” 我查看有关类型转换的MSDN文章: http : //msdn.microsoft.com/en-us/library/ms173105.aspx
speed
是否需要float
? 如果没有,你可以做
int speed;
或使用显式演员表
if (movingUp) { ballRect.Y -= (int)speed; }// No Error
也许speed
被声明为float
类型。
您可以通过将速度从float转换为整数来进行数学运算,如下所示:
public void BallMovement() { int speedInt = Convert.Int32(speed); if (movingUp) { ballRect.Y -= speedInt; } if (!movingUp) { ballRect.Y += speedInt; } if (movingLeft) { ballRect.X -= speedInt; } if (!movingLeft) { ballRect.X += speedInt; } if (ballPosition.Y < 85) { movingUp = false; } if (ballPosition.Y >= 480) { movingUp = true; } ....
另一方面,如果您希望编译器为您转换(多次),您可以使用(int)speed
转换每个引用speed
的场合。