Timer事件增加变量的值

时间:2013-05-29 12:44:15

标签: c# timer

我正在制作一个非常基本的程序,我希望球能够遵循抛物线曲线。我的想法是设置一个计时器以一定的间隔打勾,并将时间设置为我在方程中使用的变量,这也将是我的x值。

我创建了一个事件timer_Tick。每次计时器滴答时,如何增加X的值?

4 个答案:

答案 0 :(得分:2)

您需要创建类字段(例如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();
}

答案 1 :(得分:2)

这不是您问题的直接答案 - 但您可能会觉得有用。

使用Reactive Extensions(创建控制台应用程序并添加Nuget包“Rx-Testing”)是一种完全不同的方式,还演示了如何虚拟化时间,这有助于测试目的。你可以随意控制时间!

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...

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

在tick事件方法中,您可以只需x = x + value或x + = value。请注意,tick事件不会告诉您多少滴答!所以你可能还需要第二个变量来跟踪它。