I’m kinda new to programming and got a question on what is a good practice.
I created a class that represents a ball and it has a function Jump() that use 2 timers and get the ball up and down.
I know that in Winforms you got to call Invalidate() every time you want to repaint the screen, or part of it. I didn’t find a good way to do that, so I reference the form in my class, and called Invalidate() inside my ball class every time I need to repaint to ball movement.
(this works but I got a feeling that this is not a good practice)
Here is the class I created:
public class Ball
{
public Form1 parent;//----> here is the reference to the form
public Rectangle ball;
Size size;
public Point p;
Timer timerBallGoUp = new Timer();
Timer timerBallGDown = new Timer();
public int ballY;
public Ball(Size _size, Point _p)
{
size = _size;
p = _p;
ball = new Rectangle(p, size);
}
public void Jump()
{
ballY = p.Y;
timerBallGDown.Elapsed += ballGoDown;
timerBallGDown.Interval = 50;
timerBallGoUp.Elapsed += ballGoUp;
timerBallGoUp.Interval = 50;
timerBallGoUp.Start();
}
private void ballGoUp(object obj,ElapsedEventArgs e)
{
p.Y++;
ball.Location = new Point(ball.Location.X, p.Y);
if (p.Y >= ballY + 50)
{
timerBallGoUp.Stop();
timerBallGDown.Start();
}
parent.Invalidate(); // here i call parent.Invalidate() 1
}
private void ballGoDown(object obj, ElapsedEventArgs e)
{
p.Y--;
ball.Location = new Point(ball.Location.X, p.Y);
if (p.Y <= ballY)
{
timerBallGDown.Stop();
timerBallGoUp.Start();
}
parent.Invalidate(); // here i call parent.Invalidate() 2
}
}
I’m wondring if there is a better way to do that?
(sorry for my english)
You should make a
Changedevent in your ball that fires whenever the ball needs to be redrawn.You can then handle this event in the form and
Invalidate().However, it would be better to replace all of your timers with a single timer in the form which calls a public
Tick()method in each object (ball, brick, whatever).You can then do a single
Invalidate()after ticking each object.This also makes sure that all of your objects are in sync.