.NET 4.x Не получается победить Timer - C#

Узнай цену своей работы

Формулировка задачи:

Заставил эллипс бегать к точке клика мыши, но вот остановить его движение - никак не получается. Все варианты, типа "Timer.Stop()" и "Timer.Enable = false" перепробовал.. эллипс не поддаётся. Доходя до нужной точки он трясётся как руки алкаша. Как заставить его замереть?
Листинг программы
  1. using System;
  2. namespace MouseMove
  3. {
  4. public partial class Form1 : Form
  5. {
  6. double _x; //координаты эллипса
  7. double _y; //координаты эллипса
  8. double xM; //координаты мыши
  9. double yM; //координаты мыши
  10. double angle; //угол поворота
  11. double speed; //скорость движения
  12. public Form1()
  13. {
  14. InitializeComponent();
  15. _x = 50;
  16. _y = 50;
  17. angle = 0;
  18. speed = 30;
  19. }
  20. //Ищем угол между координатами сферы и курсора мыши
  21. double GetAngle()
  22. {
  23. return Math.Atan2((_x - xM), (_y - yM));
  24. }
  25. public void Form1_Paint(object sender, PaintEventArgs e)
  26. {
  27. e.Graphics.FillEllipse(Brushes.Black, (int)_x, (int)_y, 100, 100); //рисуем эллипс
  28. e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //сглаживаем движение
  29. }
  30. //Таймер
  31. public void tmrMoving_Tick(object sender, EventArgs e)
  32. {
  33. _x -= speed * Math.Sin(angle);
  34. _y -= speed * Math.Cos(angle);
  35. angle = GetAngle();
  36. Invalidate();
  37. }
  38. //Событие Клик Мыши
  39. public void Form1_MouseClick(object sender, MouseEventArgs e)
  40. {
  41. tmrMoving.Enabled = true;
  42. xM = e.X;
  43. yM = e.Y;
  44. // Проверка не получается
  45. // if (GetAngle() == 0) { tmrMoving.Enabled = false; }
  46. }
  47. }
  48. }

Решение задачи: «.NET 4.x Не получается победить Timer»

textual
Листинг программы
  1. namespace WindowsFormsApplication
  2. {
  3.     partial class MainForm
  4.     {
  5.         /// <summary>
  6.         /// Required designer variable.
  7.         /// </summary>
  8.         private System.ComponentModel.IContainer components = null;
  9.  
  10.         /// <summary>
  11.         /// Clean up any resources being used.
  12.         /// </summary>
  13.         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  14.         protected override void Dispose(bool disposing)
  15.         {
  16.             if (disposing && (components != null))
  17.             {
  18.                 components.Dispose();
  19.             }
  20.             base.Dispose(disposing);
  21.         }
  22.  
  23.         #region Windows Form Designer generated code
  24.         /// <summary>
  25.         /// Required method for Designer support - do not modify
  26.         /// the contents of this method with the code editor.
  27.         /// </summary>
  28.         private void InitializeComponent()
  29.         {
  30.             this.components = new System.ComponentModel.Container();
  31.             this.RenderingTimer = new System.Windows.Forms.Timer(this.components);
  32.             this.SuspendLayout();
  33.             //
  34.             // RenderingTimer
  35.             //
  36.             this.RenderingTimer.Interval = 200;
  37.             this.RenderingTimer.Tick += new System.EventHandler(this.RenderingTimer_Tick);
  38.             //
  39.             // MainForm
  40.             //
  41.             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  42.             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  43.             this.ClientSize = new System.Drawing.Size(284, 262);
  44.             this.DoubleBuffered = true;
  45.             this.Name = "MainForm";
  46.             this.Text = "Form";
  47.             this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint);
  48.             this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseClick);
  49.             this.ResumeLayout(false);
  50.         }
  51.         #endregion
  52.  
  53.         private System.Windows.Forms.Timer RenderingTimer;
  54.     }
  55. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

7   голосов , оценка 3.857 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы