Reputation: 106
I'm working on a very basic program where I want a ball to follow a parabolic curve. My idea is to set a timer to tick with a certain interval and set the time as an variable which I use in my equation which will also be my x-value.
I've created an event timer_Tick. How can I increase the value of X each time the timer ticks?
Upvotes: 0
Views: 7466
Reputation: 29786
This isn't a direct answer to your question - but you might find it helpful.
It's a completely different way to go that uses Reactive Extensions (create a console app and add Nuget package "Rx-Testing") and also demonstrates how you can virtualize time which can be helpful for testing purposes. You can control time as you please!
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);
}
}
}
Which gives the output:
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...
Upvotes: 3
Reputation: 236228
You need to create class field (e.g. elapsedTime
) to store value between event handler calls:
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();
}
Upvotes: 3
Reputation: 1471
First the variable needs to be declared outside of any method, which is 'class scope'
In the tick event method, you can then just x = x + value, or x += value. Note that the tick event doesn't tell you how many ticks! So you're likely to need a second variable to keep track of this too.
Upvotes: 0
Reputation: 60493
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.
}
Upvotes: 1