JavaSwing游戏开发之Camera原理
import javax.swing.*;
import java.awt.*;
public class CameraExample extends JPanel {
private static final long serialVersionUID = 1L;
private int xOffset = 0;
public CameraExample() {
// 使用双缓冲技术避免闪烁
super(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// 绘制背景
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 640, 480);
// 绘制实体
g2d.setColor(Color.BLUE);
g2d.fillRect(200 + xOffset, 100, 20, 20);
// 绘制Camera边界
g2d.setColor(Color.RED);
g2d.drawRect(100 + xOffset, 50, 200, 200);
}
public void moveCamera(int x) {
xOffset = x;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Camera Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CameraExample());
frame.setSize(640, 480);
frame.setVisible(true);
// 模拟移动Camera
CameraExample cameraExample = (CameraExample) frame.getContentPane().getComponent(0);
for (int i = -100; i < 100; i++) {
cameraExample.moveCamera(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
这段代码演示了如何在Java Swing中实现一个简单的Camera效果。它创建了一个CameraExample类,继承自JPanel,并重写了paintComponent方法来绘制屏幕上的对象。moveCamera方法用于移动Camera并重绘组件。在主方法中,我们创建了一个JFrame,添加了CameraExample的实例,并模拟了Camera的移动。
原文地址:https://blog.csdn.net/Rverdoser/article/details/145210959
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!