I have a program that counts collisions.

Code

int eatenAppleCount = 0;

public MainPage()
{
score.Content = "Score" + " " + Convert.ToString(eatenAppleCount);   
}

 for (int indx = myapples.Count - 1; indx >= 0; indx--)
            {
                myapples[indx].Update(LayoutRoot);
                bool collided = DetectCollision(myapples[indx], myPig);
                if (collided)
                {
                    eatenAppleCount ++;
                    RemoveApple(myapples[indx]);
                }
            }

Problem is the score just reads 0 even on collisions. Can someone help me and I do not understand why it is not incrementing.

有帮助吗?

解决方案

You need to execute your code for calculating eatenAppleCount before showing it in the message.

It appears you are just using the default value of eatenAppleCount and then you are calculating it.

int eatenAppleCount = 0;

public MainPage()
{

    for (int indx = myapples.Count - 1; indx >= 0; indx--)
    {
        myapples[indx].Update(LayoutRoot);
        bool collided = DetectCollision(myapples[indx], myPig);
        if (collided)
        {
            eatenAppleCount ++;
            RemoveApple(myapples[indx]);
        }
    }

    score.Content = "Score" + " " + Convert.ToString(eatenAppleCount);   

}

其他提示

You got several code snipets so hard to follow a bit, but I think you just need to reapply this line after the increment:

score.Content = "Score" + " " + Convert.ToString(eatenAppleCount);

Using a variable to create a string to use as content doesn't link that variable to the content. When the variable changes, it doesn't affect content created from the previous value.

You need to update the content when the variable changes. Put that code from the constructor in a method, so that you can call it both from the constructor, and when you want to update the content.

You need to pass this variable as reference

int eatenAppleCount = 0;

public MainPage()
{
   CollisionDetect(ref eatenAppleCount);
   score.Content = "Score" + " " + Convert.ToString(eatenAppleCount);   
}

protected void CollisionDetect(ref eatenAppleCount)
{
    for (int indx = myapples.Count - 1; indx >= 0; indx--)
    {
         myapples[indx].Update(LayoutRoot);
         bool collided = DetectCollision(myapples[indx], myPig);
         if (collided)
         {
             eatenAppleCount ++;
             RemoveApple(myapples[indx]);
         }
     }        
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top