Problem z timerami, metoda nie zmienia sx rec'a

0

Witam, moja metoda ma przemieszczać rec o 25 w ciągu 1000ms przez cały czas. Czy moglibyście zobaczyć na ten kod i powiedzieć dlaczego ta metoda się nie wykonuje?

using Timer = System.Timers.Timer;

namespace CSSnake
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int sx = 0;
        int sy = 0;

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Rectangle rec = new Rectangle(sx, sy, 25, 25);
            SolidBrush white = new SolidBrush(Color.White);
            g.FillRectangle(white, rec);
        }

        private Timer timer;

        public void Timer()
        {
            timer = new Timer();
            timer.Interval = 1000;
            timer.Elapsed += new ElapsedEventHandler(sxsyMove);


        }
        private void sxsyMove(object sender, EventArgs e)
        {
            sx += 25;
        }
    }
    }

Pozdrawiam.

0

Wydaje mi się, że musisz kwadrat narysować jeszcze raz. Nie bardzo wiem jak to jest w grafikach C#, ale chyba nie ma eventu na OnChangePosition(). W twoim sxsyMove() musisz narysować kwadrat z nowym położeniem, a poprzedni usunąć.

0

Zmiany poniżej

using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;

namespace CSSnake
{
    public partial class Form1 : Form
    {
        private System.Timers.Timer timer;
        private int sx = 0;
        private int sy = 0;
        
        public Form1()
        {
            InitializeComponent();
            ConfigTimer();
        }
        public void ConfigTimer()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Elapsed += sxsyMove;
            timer.Start();
        }

        private void DrawRec()
        {
            Graphics g = this.CreateGraphics();
            g.Clear(Color.LightGray);
            Rectangle rec = new Rectangle(sx, sy, 25, 25);
            SolidBrush white = new SolidBrush(Color.Red);
            g.FillRectangle(white, rec);
        }

        private void sxsyMove(object sender, EventArgs e)
        {
            **DrawRec();**
            sx += 25;
        }
    }
}
0

Najpierw zwiększ liczbę, a później rysuj. Kod wykonuje od góry do dołu, jeśli narysujesz kwadrat, a później zmienisz sx to efekt będzie ten sam co w twoim wcześniejszym kodzie. Dopiero drugie wywołanie timera spowoduje twoją pierwszą zmianę pozycji.

        private void sxsyMove(object sender, EventArgs e)
        {
            sx += 25;
            **DrawRec();**
        }

1 użytkowników online, w tym zalogowanych: 0, gości: 1