C#2D游戏引擎开发

时间:2014-10-04 13:13:56

标签: c# game-engine

我一直想用C#开发2D游戏。现在,我之前已经在Java中完成了这个,但我似乎找不到任何具有类似语法的东西。

我的Java游戏引擎的主要游戏类如下:

package Main;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

import GameState.GameStateManager;

public class GamePanel extends JPanel implements Runnable, KeyListener
{
    //Dimensions
    public static final int HEIGHT = 240;
    public static final int WIDTH = 320;//(HEIGHT/9)*16;//360
    public static final int SCALE = 3;

    //Game Thread
    private Thread thread;
    private boolean running;
    private int FPS = 60;
    private long targetTime = 1000/FPS;

    //Image
    private BufferedImage image;
    private Graphics2D g;

    //Game State Manager
    private GameStateManager gsm;

    public GamePanel()
    {
        super();
        setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
        setFocusable(true);
        requestFocus();
    }

    public void addNotify()
    {
        super.addNotify();
        if(thread == null)
        {
            thread = new Thread(this);
            addKeyListener(this);
            thread.start();
        }
    }

    private void init()
    {
        image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
        g = (Graphics2D)image.getGraphics();
        running = true;
        gsm = new GameStateManager();
    }

    public void run()
    {
        init();

        long start;
        long elapsed;
        long wait;

        //Game loop
        while(running)
        {
            start = System.nanoTime();

            update();
            draw();
            drawToScreen();

            elapsed = System.nanoTime() - start;
            wait = targetTime - elapsed / 1000000;

            if(wait <= 0)
            {
                wait = 1;
            }
            try 
            {
                Thread.sleep(wait);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    private void update()
    {
        gsm.update();
    }
    private void draw()
    {
        gsm.draw(g);
    }
    private void drawToScreen()
    {
        Graphics g2 = getGraphics();
        g2.drawImage(image, 0, 0, WIDTH*SCALE, HEIGHT*SCALE, null);
        g2.dispose();
    }

    public void keyTyped(KeyEvent key){}
    public void keyPressed(KeyEvent key)
    {
        gsm.keyPressed(key.getKeyCode());
    }
    public void keyReleased(KeyEvent key)
    {
        gsm.keyReleased(key.getKeyCode());
    }
}

那里有关于引擎开发的体面教程吗?有没有办法在C#中实现上面的代码?我想避免使用预制引擎。

提前致谢。

1 个答案:

答案 0 :(得分:1)

我建议你试试MonoGame。它是XNA的开源实现,已经停止使用。它的运行类似于你的Java代码,主要的游戏循环和每个循环运行的方法,所以它不应该很难移植,特别是如果你刚刚开始。值得注意的是,MonoGame是开源和跨平台的。