两个变量在更改后共享相同的值

时间:2017-11-03 14:46:18

标签: c# winforms

我试图建立一个弹跳球计划,我在改变球移动的角度方面遇到了麻烦。

我已将变量声明如下:

    int xDelta;
    int yDelta;

    int speed;
    int savedSpeed;

    int iXSize; //size of width of window
    int iYSize; //size of height of window

我在Form1函数中初始化xDelta,yDelta和speed:

    public Form1()
    {
        //
        // Required for Windows Form Designer support
        //
        InitializeComponent();
        xDelta = 3;
        yDelta = 3;
        speed = 5;
        ...

为了移动球,我有

    private void timer1_Tick(object sender, System.EventArgs e)
    {
        //DrawBall();                       // Draw ball in next frame of animation


        if (stopped != 1)
        {
            if (xDelta != 0)
            {
                ballRect.X += speed * (xDelta / Math.Abs(xDelta));
            }
            if (yDelta != 0)
            {
                ballRect.Y += speed * (yDelta / Math.Abs(yDelta));
            }


            if (ballRect.X + radius >= ClientSize.Width || ballRect.X + radius <= 0)
                xDelta = -xDelta;

            if (ballRect.Y + radius >= ClientSize.Height || ballRect.Y + radius <= 0)
                yDelta = -yDelta;

            this.Invalidate();
        }
    }

要改变球的角度,我有两个功能:

    private void button3_Click(object sender, EventArgs e)
    {
        //+Angle
        //Move clockwise
        Debug.WriteLine("Before: xDelta: {0} yDelta: {0}", xDelta, yDelta);
        xDelta++;
        yDelta--;
        Debug.WriteLine("After: xDelta: {0} yDelta: {0}", xDelta, yDelta);


    }

    private void button4_Click(object sender, EventArgs e)
    {
        //-Angle
        Debug.WriteLine("Before: xDelta: {0} yDelta: {0}", xDelta, yDelta);
        xDelta--;
        yDelta++;
        Debug.WriteLine("After: xDelta: {0} yDelta: {0}", xDelta, yDelta);
    }

由于某种原因,我的WriteLine语句的输出始终输出xDelta和yDelta以具有相同的值。例如:

+角度按钮

Before: xDelta: -3 yDelta: -3
After: xDelta: -2 yDelta: -2
Before: xDelta: -2 yDelta: -2
After: xDelta: -1 yDelta: -1

-Angle Button

Before: xDelta: -1 yDelta: -1
After: xDelta: -2 yDelta: -2
Before: xDelta: 2 yDelta: 2
After: xDelta: 1 yDelta: 1

为什么会这样?

2 个答案:

答案 0 :(得分:3)

您正在使用{0}占位符两次:

    Debug.WriteLine("Before: xDelta: {0} yDelta: {0}", xDelta, yDelta);

使用{1}代替

    Debug.WriteLine("Before: xDelta: {0} yDelta: {1}", xDelta, yDelta);

或者,从C#6.0开始,您可以使用字符串插值

 Debug.WriteLine($"Before: xDelta: {xDelta} yDelta: {yDelta}");

答案 1 :(得分:1)

正如评论中所提到的,您正在重复WriteLine字符串中的参数。您可以使用interpolated strings

来避免此类事故

而不是

Debug.WriteLine("Before: xDelta: {0} yDelta: {0}", xDelta, yDelta);

DO

Debug.WriteLine($"Before: xDelta: {xDelta} yDelta: {yDelta}");