1

我有一个弹跳球,我试着让它弹跳一次,速度会变快。

在我的球课上,我有一个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 < 85)
    {
        movingUp = false;
    }
    if (ballPosition.Y >= 480)
    {
        movingUp = true;
    }

然后我在更新方法中添加这个:BallMovement();

在我尝试使用速度变量之前它工作,由于这个错误它不会编译:

无法将类型“float”隐式转换为“int”。存在显式转换(您是否缺少强制转换?)

4

4 回答 4

1

速度需要浮动。如果您想将速度保持为浮动,您可以创建自己的矩形结构。你可以这样做:

        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。高温高压

于 2013-07-29T23:30:16.920 回答
1

也许speed被声明为 type 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;
    }
    ....

另一方面,如果您希望编译器为您转换它(多次),您可以转换您speed使用(int)speed.

于 2013-07-29T21:46:34.817 回答
1

您正在尝试从 int(例如:12)中减去浮点值(例如:1.223488);你不能这样做。将两个值都转换(转换)为浮点数,或者将两个值转换(转换)为整数:

 if (movingUp) { ballRect.Y -= (int)speed; }//Error

该错误基本上是说“我们无法自动为您转换(隐式),但您可以自己转换(显式)。” 我会查看有关类型转换的 MSDN 文章:http: //msdn.microsoft.com/en-us/library/ms173105.aspx

于 2013-07-29T21:46:36.447 回答
1

speed需要吗float?如果没有,你可以做

int speed;

或使用显式强制转换

if (movingUp) { ballRect.Y -= (int)speed; }// No Error
于 2013-07-29T21:52:21.347 回答