Search code examples
c#xnapong

Cannot Implicitly Convert Type in XNA


i have a bouncing ball, and i tried to make so when it bounces once, the speed gets higher.

In my ball class, i have a float speed;

and i initialized it: public ball(float speed) speed = 1f;

I have a method for my ball movement, that looks like this:

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;
    }

I then add this in the update method: BallMovement();

It worked before i tried to use the speed variable, it won't compile because of this error:

Cannot implicitly convert type 'float' to 'int'.An explicit conversion exists(are you missing a cast?)


Solution

  • The speed needs to be float. If you want to keep the speed as a float, you could create your own rectangle structure. You could do something like this:

            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;
            }
        }
    

    The intersection checking won't be absolutely perfect, but at least your rectangle's X and Y could have 0.5 added on to them. HTH