I have a cube and there is a need to add a 3D coordinate system to it.
There is an example my coordinate system with a cube should approximtely look like:
Unfortunately, my progress seems so far from this example:
Maybe, I can find out how to draw X and Y axis, but I have no idea how to add the Z axis. So, how to build the right coordinate sytem?
My code:
import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;
public class Cube extends JPanel {
double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},
{1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};
int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};
public Cube() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
scale(50);
rotateCube(Math.toRadians(60), Math.toRadians(10), Math.toRadians(0));
}
final void scale(double s) {
for (double[] node : nodes) {
node[0] *= s;
node[1] *= s;
node[2] *= s;
}
}
final void rotateCube(double angleX, double angleY, double angleZ) {
double sinX = sin(angleX);
double cosX = cos(angleX);
double sinY = sin(angleY);
double cosY = cos(angleY);
double sinZ = sin(angleZ);
double cosZ = cos(angleZ);
for (double[] node : nodes) {
double x = node[0];
double y = node[1];
double z = node[2];
node[0] = x * cosX - z * sinX;
node[2] = z * cosX + x * sinX;
z = node[2];
node[1] = y * cosY - z * sinY;
node[2] = y * sinY + z * cosY;
x = node[0];
y = node[1];
node[0] = x * cosZ + y * sinZ;
node[1] = y * cosZ - x * sinZ;
}
}
void drawCube(Graphics2D g) {
g.translate(getWidth() / 2, getHeight() / 2);
g.setColor(Color.BLACK);
for (int[] edge : edges) {
double[] xy1 = nodes[edge[0]];
double[] xy2 = nodes[edge[1]];
g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),
(int) round(xy2[0]), (int) round(xy2[1]));
}
for (double[] node : nodes)
g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8);
}
void drawAxis(Graphics2D g) {
int x_c = getWidth() / 2;
int y_c = getHeight() / 2;
// X - axis
g.setColor(Color.green);
g.drawLine(round(x_c + 300), round(y_c), round(x_c), round(y_c));
// Y- axis
g.setColor(Color.blue);
g.drawLine(round(x_c), round(y_c), round(x_c), round(y_c) + 300);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawAxis(g);
drawCube(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Rotating Cube");
f.setResizable(false);
f.add(new Cube(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}