C# 用于增加变量值的计时器事件

C# 用于增加变量值的计时器事件,c#,timer,C#,Timer,我正在做一个非常基本的程序,我想让球沿着抛物线运动。我的想法是设置一个计时器,以一定的间隔计时,并将时间设置为一个变量,我在等式中使用它,它也将是我的x值 我已经创建了一个事件计时器。如何在每次计时器计时时增加X的值?首先,需要在任何方法之外声明变量,即“类范围” private int myVar= 0;//private field which will be incremented void timer_Tick(object sender, EventArgs e)//event on

我正在做一个非常基本的程序,我想让球沿着抛物线运动。我的想法是设置一个计时器,以一定的间隔计时,并将时间设置为一个变量,我在等式中使用它,它也将是我的x值


我已经创建了一个事件计时器。如何在每次计时器计时时增加X的值?

首先,需要在任何方法之外声明变量,即“类范围”

private int myVar= 0;//private field which will be incremented

void timer_Tick(object sender, EventArgs e)//event on timer.Tick
{
            myVar += 1;//1 or anything you want to increment on each tick.
}

在tick事件方法中,您可以只选择x=x+value或x+=value。请注意,滴答声事件不会告诉您有多少滴答声!因此,您可能还需要另一个变量来跟踪此情况。

您需要创建类字段(例如,
elapsedTime
)来存储事件处理程序调用之间的值:

private int elapsedTime; // initialized with zero
private Timer timer = new System.Windows.Forms.Timer();

public static int Main() 
{
    timer.Interval = 1000; // interval is 1 second
    timer.Tick += timer_Tick;
    timer.Start();
}

private void timer_Tick(Object source, EventArgs e) {
    elapsedTime++; // increase elapsed time 
    DrawBall();
}

这不是对你问题的直接回答,但你可能会发现它很有帮助

这是一种完全不同的方式,它使用反应式扩展(创建控制台应用程序并添加Nuget软件包“Rx测试”),还演示了如何虚拟化时间,这对测试目的很有帮助。你可以随心所欲地控制时间

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;

namespace BallFlight
{
    class Program
    {
        static void Main()
        {
            var scheduler = new HistoricalScheduler();
            // use this line instead if you need real time
            // var scheduler = Scheduler.Default;

            var interval = TimeSpan.FromSeconds(0.75);

            var subscription =
                Observable.Interval(interval, scheduler)
                          .TimeInterval(scheduler)
                          .Scan(TimeSpan.Zero, (acc, cur) => acc + cur.Interval)
                          .Subscribe(DrawBall);

            // comment out the next line of code if you are using real time
            // - you can't manipulate real time!
            scheduler.AdvanceBy(TimeSpan.FromSeconds(5));

            Console.WriteLine("Press any key...");
            Console.ReadKey(true);

            subscription.Dispose();
        }

        private static void DrawBall(TimeSpan t)
        {
            Console.WriteLine("Drawing ball at T=" + t.TotalSeconds);
        }
    }
}
它给出了输出:

Drawing ball at T=0.75
Drawing ball at T=1.5
Drawing ball at T=2.25
Drawing ball at T=3
Drawing ball at T=3.75
Drawing ball at T=4.5
Press any key...

您是否有一些代码显示您已尝试/当前获得的内容?创建类字段
x
,用于存储经过的时间