I am doing a mouse race game with winforms and C#. The elements are supposed to move accordingly to their Move function but when they move the last elements stills appear instead of moving to another place or in other words invalidating the last element appeared.
This is my Form:
<pre>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace MyMouseGame
{
public partial class Form1 : Form
{
Graphics g;
Pen p = new Pen(Color.Black);
ElementClass[] factory;
const int NUM = 5;
private static Random R = new Random();
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
g = panel1.CreateGraphics();
}
public void threadCounter()
{
int counter = 0;
while (true)
{
counter++;
this.Invoke(new Action(() =>
{
lcountRes.Text = counter.ToString();
}));
Thread.Sleep(1000);
}
}
public int generateRandomNum(int start, int end)
{
int randomNum = R.Next(start, end);
return randomNum;
}
public ElementClass[] ElementsFactory()
{
int i = NUM;
ElementClass[] shapesArr = new ElementClass[NUM];
while (i > 0)
{
int numOfShape = generateRandomNum(1, 4);
switch (numOfShape)
{
case 1:
shapesArr[i-1] = new E_Random();
break;
case 2:
shapesArr[i-1] = new E_Chase();
break;
case 3:
shapesArr[i-1] = new E_Escape();
break;
default:
break;
}
i--;
}
return shapesArr;
}
private void Form1_Load(object sender, EventArgs e)
{
factory = ElementsFactory();
}
private void button1_Click(object sender, EventArgs e)
{
Thread counterThread = new Thread(threadCounter);
counterThread.Start();
t.Interval = 100;
t.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i < NUM; i++)
{
factory[i].Draw(g, p);
factory[i].MoveElement();
}
this.Invalidate();
}
}
}
And another question: I need to move one of the elements far from the Mouse Position.
I attach my code. By now it is going on the mouse direction and not the opposite.
public override void MoveElement() {
rect.X += move_x;
rect.Y += move_y;
double dif_x = MousePosition.X - rect.X;
double dif_y = MousePosition.Y - rect.Y;
move_x = (int)(dif_x / 20);
move_y = (int)(dif_y / 20);
}
Thanks a lot.
What I have tried:
I've tried Invalidate() and this.Invalidate() but doensnt work. Also tried Refresh() but it is not what I need. Maybe I should put them in a different place?