سؤال

I am trying to spawn enemies and move them from left to right with a timer how can i do this?

Example:

int count;
timer (every 1 sec)
{
    Enemy somename+count = new Enemy();
    count++;
}

timer (every 0.001 sec)
{
    somename+count.x++;
}
هل كانت مفيدة؟

المحلول 2

Your fundamental problem seems to be lacking a way to store references to all of your enemies. Generics and collections provide a solution to this type of problem. I'll use a List<T>, which is the most basic such collection. There are many others, however, that each have their own useful properties.

Consider :

private class Enemy
{
    public int position;
}

private List<Enemy> enemyList = new List<Enemy>();

private void timer1_Tick(object sender, EventArgs e)
{
    enemyList.Add(new Enemy());  
}

private void timer2_Tick(object sender, EventArgs e)
{
    foreach(Enemy enemy in enemyList)
    {
        enemy.position++;
    }
}

Also consider that updating a large list of visual objects every 0.001 second is useless and wasteful. One millisecond updates correspond to 1000fps. No video device will update that fast and no human being can see that fast. Generally, for real-time updates you should aim to update between 30-60fps. That corresponds to no more frequently than about 0.016s (16ms).

نصائح أخرى

If this is an assignment, and to get it up and running. Just use the Timer class. You will not get as high resolution as 1000hz (1ms) as you wished for the movement though.

Documentation: Timer class

        var timerCreate = new Timer {Interval = 1000};
        timerCreate.Tick += delegate(object o, EventArgs args)
        {
            // create them 
        };

        var timerAction = new Timer {Interval = 50};
        timerAction.Tick += delegate(object o, EventArgs args)
        {
            // move them            
        };

As you are creating, the enemies inside a local scope, you cannot access them, once you get out of the loop. Instead, have a list and add your newly spawned enemies to this list. Maintain two threads for doing your two tasks. 1) Thread - 1 will add spawn enemies add adds enemies to our list. 2) Thread -2 will move the enemies in our spawned list. But, as out list is a shared resource between both the threads, always access the list using 'locks'.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top