Reputation: 1
OK, so I'm creating a pacman game in c# and I've got the pacman down. Now I'm trying to get my monsters in to the game.
I've created a class with moving methods and everything. Now the problem is that I'm drawing the monster and the pacman on a different graphics object. They are both the size of my panel and when I run the code only the pacman shows up, the monster is working but it's underneath the graphics object that the pacman is moving on.
This the code of drawing both the monster and pacman:
private void timMove_Tick(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(panBox.Width, panBox.Height);
Graphics g = Graphics.FromImage(bitmap);
foreach (Monster mon in monsters)
{
mon.move(g);
}
foreach (Pacman pac in characters)
{
pac.move(g);
}
Graphics g2 = panBox.CreateGraphics();
g2.DrawImage(bitmap, 0, 0);
}
My question is: how to either make them drawing on the same graphics object, or that they both just show instead of right now only the pacman?
Upvotes: 0
Views: 703
Reputation: 348
I think you should think about your class structure in general. I would recommend using something like this as a starting point:
abstract class GameObject
{
public abstract void Move();
public abstract void Draw(Graphics g);
}
class Pacman : GameObject
{
public override void Move()
{
//Update the Position of Pacman, check for collisions, ...
}
public override void Draw(Graphics g)
{
//Draw Pacman at his x and y coordinates
}
}
class Monster : GameObject
{
public override void Move()
{
//Update the Position of the Monster, ...
}
public override void Draw(Graphics g)
{
//Draw the Monster at his current position
}
}
class GameClass
{
private Pacman _pacman;
private Monster _monster;
private List<GameObject> _gameobjects = new List<GameObject>();
public GameClass()
{
_pacman = new Pacman();
_monster = new Monster();
_gameobjects.Add(_pacman);
_gameobjects.Add(_monster);
}
private void TimerTick()
{
//update all GameObjects
foreach (var gameobject in _gameobjects)
{
gameobject.Move();
}
//Draw every single GameObject to the Bitmap
Bitmap bitmap = new Bitmap(panBox.Width, panBox.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
foreach (var gameobject in _gameobjects)
{
gameobject.Draw(g);
}
}
//Draw the Bitmap to the screen
using (Graphics g = panBox.CreateGraphics())
{
g.DrawImage(bitmap, 0, 0);
}
}
You should take a look at Inheritance/Polimorphism and Classes in general. Polimorphism: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/polymorphism Classes: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes
Upvotes: 1