我刚开始学习游戏编程,在大学学习了 1 个学期的课程后,所以我认为我已经准备好并且我真的很想这样做,所以首先:1)什么是好的学习资源?Ive googlef 很多,有两本书:Killer Game Programming in Java 和 Begining java SE6 game programming。一个过于具体又不具体,另一个解释得很少,所以很难理解什么是什么。尤其是渲染、缓冲区、如何渲染到小程序、框架和面板。任何帮助将不胜感激;)谢谢!
我写了一个非常基本的代码,移动一个盒子,一切都很好,但是盒子不在中间,因为它应该是:
物体:
package milk;
public class Thing
{
double x,y;
Shape shape;
int[] thingx={-5,5,5,-5};
int[] thingy={5,5,-5,-5};
Thing(double x, double y)
{
setX(x);
setY(y);
setShape();
}
public void setX(double x)
{
this.x=x;
}
public void setY(double y)
{
this.y=y;
}
public void setShape()
{
this.shape=new Polygon(thingx,thingy,thingx.length);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public Shape getShape()
{
return shape;
}
public void incX(int i)
{
this.x+=i;
}
public void incY(int i)
{
this.y+=i;
}
}
面板:
package milk;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class MilkPanel extends JPanel implements Runnable, KeyListener{
Thread animator;
Graphics2D g2d;
Thing thing=new Thing(320,240);
AffineTransform identity = new AffineTransform();
MilkPanel()
{
setSize(640,480);
setBackground(Color.black);
setFocusable(true);
requestFocus();
addKeyListener(this);
}
public void addNotify()
{
super.addNotify();
animator = new Thread(this);
animator.start();
}
public void paint(Graphics g)
{
g2d=(Graphics2D)g;
g2d.setColor(Color.black);
g2d.fillRect(0, 0, getSize().width,getSize().height);
drawThing();
g.dispose();
}
public void drawThing()
{
g2d.setTransform(identity);
g2d.translate(thing.getX(), thing.getY());
g2d.setColor(Color.orange);
g2d.draw(thing.getShape());
}
public void run()
{
while(true)
{
try
{
Thread.sleep(20);
}
catch(Exception e)
{
}
repaint();
}
}
public void keyPressed(KeyEvent e)
{
int key=e.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
thing.incY(-5);
break;
case KeyEvent.VK_DOWN:
thing.incY(5);
break;
case KeyEvent.VK_RIGHT:
thing.incX(5);
break;
case KeyEvent.VK_LEFT:
thing.incX(-5);
break;
}
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
}
主要的:
package milk;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class MilkIt extends JFrame {
public MilkIt() {
add(new MilkPanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(640,480);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MilkIt();
}
}