import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class DrawCube extends Canvas{
public int screenW=600;
public int screenH=400;
public DrawCube() {
setSize(screenW,screenH);
setBackground(Color.white);
setForeground(Color.black);
JFrame f=new JFrame();
f.setTitle("Graphics Test");
f.setSize(screenW,screenH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setVisible(true);
}
public void paint(Graphics g) {
//立方体の頂点の定義
double[][] vertices= {
{-100,-100,-100},
{ 100,-100,-100},
{ 100, 100,-100},
{-100, 100,-100},
{-100,-100, 100},
{ 100,-100, 100},
{ 100, 100, 100},
{-100, 100, 100}
};
//立方体の面の定義
int[][] faces= {
{0,1,2,3},
{1,5,6,2},
{2,6,7,3},
{3,7,4,0},
{0,4,5,1},
{6,7,4,5},
};
int[] px=new int[4];
int[] py=new int[4];
for(int i=0;i<6;i++) {
for(int j=0;j<4;j++) {
double x=vertices[faces[i][j]][0];
double y=vertices[faces[i][j]][1];
double z=vertices[faces[i][j]][2];
//y軸回転
double alpha=25*Math.PI/180;
double x1=x*Math.cos(alpha)+z*Math.sin(alpha);
double y1=y;
double z1=-x*Math.sin(alpha)+z*Math.cos(alpha);
//x軸回転
double beta=-30*Math.PI/180;
double x2=x1;
double y2=y1*Math.cos(beta)-z1*Math.sin(beta);
double z2=y1*Math.sin(beta)+z1*Math.cos(beta);
//透視投影変換(投影点z0を500とした場合)
x2=x2/(1-z2/500);
y2=y2/(1-z2/500);
//座標原点移動
px[j]=(int)x2+screenW/2;
py[j]=(int)y2+screenH/2;
}
g.drawPolygon(px, py, 4);
}
}
public static void main(String[] args) {
new DrawCube();
}
}
</code>
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class DrawCube extends Canvas{
public int screenW=600;
public int screenH=400;
public DrawCube() {
setSize(screenW,screenH);
setBackground(Color.white);
setForeground(Color.black);
JFrame f=new JFrame();
f.setTitle("Graphics Test");
f.setSize(screenW,screenH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setVisible(true);
}
public void paint(Graphics g) {
//立方体の頂点の定義
double[][] vertices= {
{-100,-100,-100},
{ 100,-100,-100},
{ 100, 100,-100},
{-100, 100,-100},
{-100,-100, 100},
{ 100,-100, 100},
{ 100, 100, 100},
{-100, 100, 100}
};
//立方体の面の定義
int[][] faces= {
{0,1,2,3},
{1,5,6,2},
{2,6,7,3},
{3,7,4,0},
{0,4,5,1},
{6,7,4,5},
};
int[] px=new int[4];
int[] py=new int[4];
for(int i=0;i<6;i++) {
for(int j=0;j<4;j++) {
double x=vertices[faces[i][j]][0];
double y=vertices[faces[i][j]][1];
double z=vertices[faces[i][j]][2];
//y軸回転
double alpha=25*Math.PI/180;
double x1=x*Math.cos(alpha)+z*Math.sin(alpha);
double y1=y;
double z1=-x*Math.sin(alpha)+z*Math.cos(alpha);
//x軸回転
double beta=-30*Math.PI/180;
double x2=x1;
double y2=y1*Math.cos(beta)-z1*Math.sin(beta);
double z2=y1*Math.sin(beta)+z1*Math.cos(beta);
//平行投影変換
x2=x2;
y2=y2;
//座標原点移動
px[j]=(int)x2+screenW/2;
py[j]=(int)y2+screenH/2;
}
g.drawPolygon(px, py, 4);
}
}
public static void main(String[] args) {
new DrawCube();
}
}
</code>