Куб вращается неправильно?JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Куб вращается неправильно?

Сообщение Anonymous »

Итак, у меня есть простая программа, которая имеет объект Game game, который затем имеет объект CANVAS Canvas, расширяющий JPanel, и логический объект, оба реализуют Runnable и запускаются двумя потоками из объекта игры.
Затем у меня есть объект POLYGON, который может читать файл. Я прочитал файл, содержащий данные для куба (точки и числа для рисования линий), как показано ниже:
s -1.0 -1.0 -1.0 =
s 1.0 -1.0 -1.0 =
s 1.0 1.0 -1.0 =
s -1.0 1.0 -1.0 =
s -1.0 -1.0 1.0 =
s 1.0 -1.0 1.0 =
s 1.0 1.0 1.0 =
s -1.0 1.0 1.0 =

f 0 1 2 3 =
f 4 5 6 7 =
f 0 4 7 3 =
f 1 5 6 2 =
f 0 4 5 1 =
f 3 7 6 2 =

Что происходит после того, как точки (или объекты SPOT, содержащие значения x, y и z) отображаются. нужного размера и сохраняется в отдельном массиве. Я попробовал распечатать значения, и они такие, как и должно быть.
В функции обновления многоугольника я просматриваю массив точек и создаю точку из увеличенной точки, сложенной вместе. с позиционированной точкой, в результате чего создается новая точка, которая затем передается через функцию вращения и сохраняется в отдельном массиве для рисования.
this.rotation = this.rotation.Add(new SPOT(0.1, 0.1, 0.1));
for(int i = 0; i < this.point.length; i++){
SPOT r = this.RotatePoint(this.scaled.Get(i).Add(this.positioned.Get(i)));
// ^-- Rotation function returning point from size + position.
this.painted.Position(r,i);
}

Проблема в том, что куб не сохраняет свою форму куба, как это видно на изображениях ниже:
Изображение
[img]https://i.stack. imgur.com/3HuCu.png[/img]

Еще одна картинка начала розыгрыша, где куб в форме (без перспективы/проекции):
Изображение

Моя функция вращения, как Не могу понять, в чем еще может быть проблема:
public SPOT RotatePoint(SPOT g){
double sx = Math.sin(Math.toRadians(this.rotation.x)), sy = Math.sin(Math.toRadians(this.rotation.y)), sz = Math.sin(Math.toRadians(this.rotation.z));
double cx = Math.cos(Math.toRadians(this.rotation.x)), cy = Math.cos(Math.toRadians(this.rotation.y)), cz = Math.cos(Math.toRadians(this.rotation.z));
SPOT spot = g;
g.y = (cx * (spot.y - this.center.y) - sx * (spot.z - this.center.z)) + this.center.y;
g.z = (sx * (spot.y - this.center.y) + cx * (spot.z - this.center.z)) + this.center.z;
//spot = g;
g.x = (cy * (spot.x - this.center.x) + sy * (spot.z - this.center.z)) + this.center.x;
g.z = (sy * (spot.x - this.center.x) - cy * (spot.z - this.center.z)) + this.center.z;
//spot = g;
g.x = (cz * (spot.x - this.center.x) - sz * (spot.y - this.center.y)) + this.center.x;
g.y = (cz * (spot.y - this.center.y) + sz * (spot.x - this.center.x)) + this.center.y;
return g;
}

Если я попробую вращать только по осям X или Y (закомментировав остальное), куб будет вращаться нормально, сохраняя свою форму.
Я пробовал следовать нескольким примерам и часами искал помощь, но, похоже, каждый раз получал один и тот же результат — искаженный куб.
Буду очень признателен за любую помощь, и при необходимости я предоставлю дополнительную информацию.
Как и просили, это простая программа с возможностью копирования, использующая тот же код, что и я, те же значения и функции, просто сведенные к минимуму. Несколько воспроизвожу проблему.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

public class LINE {
public LINE () {
this.slope = 0.0;
this.start = 0.0;
this.steps = 0.0;
this.end = 0.0;
this.rev = false;
}

public double slope, start, steps, end;
public boolean rev;

public void Calc(Point3D from, Point3D to){
Point3D a = from, b = to;
double slope = 0.0, steps = 0.0, start = 0.0, end = 0.0;
boolean rev = false;
if(a.x != b.x) slope = (b.y - a.y) / (b.x - a.x);

if(a.x != b.x && Math.abs(slope) b.x){
a = to;
b = from;
}
start = a.x;
end = b.x;
steps = a.y - slope * a.x;
} else {
if(a.y > b.y){
a = to;
b = from;
}
slope = (b.x - a.x) / (b.y - a.y);
start = a.y;
end = b.y;
steps = a.x - slope * a.y;
rev = true;
}
this.slope = slope;
this.end = end;
this.start = start;
this.rev = rev;
this.steps = steps;
}
}

static public class Point3D {
public Point3D (double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Point3D (int x, int y, int z) {
this.x = (double)x;
this.y = (double)y;
this.z = (double)z;
}
public double x, y, z;

}

public Main () {

}

public static Point3D[] points = new Point3D[8], draw = new Point3D[8];
public static int[][] lines = new int[6][4];
public static Point3D center = new Point3D(0, 0, 0);
public static Point3D rotation = new Point3D(0, 0, 0);

public static void main(String[] args){

JFrame frame = new JFrame();
Dimension size = new Dimension(640, 480);
Main canvas = new Main();
canvas.setPreferredSize(size);
canvas.setBackground(new Color(0, 0, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(canvas);
frame.pack();
frame.setLocation(10, 10);
frame.setTitle("Title");
frame.setVisible(true);

points[0] = new Point3D(100, 100, 100);
points[1] = new Point3D(200, 100, 100);
points[2] = new Point3D(200, 200, 100);
points[3] = new Point3D(100, 200, 100);
points[4] = new Point3D(100, 100, 200);
points[5] = new Point3D(200, 100, 200);
points[6] = new Point3D(200, 200, 200);
points[7] = new Point3D(100, 200, 200);

draw[0] = new Point3D(100, 100, 100);
draw[1] = new Point3D(200, 100, 100);
draw[2] = new Point3D(200, 200, 100);
draw[3] = new Point3D(100, 200, 100);
draw[4] = new Point3D(100, 100, 200);
draw[5] = new Point3D(200, 100, 200);
draw[6] = new Point3D(200, 200, 200);
draw[7] = new Point3D(100, 200, 200);

lines[0][0] = 0;
lines[0][1] = 1;
lines[0][2] = 2;
lines[0][3] = 3;

lines[1][0] = 4;
lines[1][1] = 5;
lines[1][2] = 6;
lines[1][3] = 7;

lines[2][0] = 0;
lines[2][1] = 4;
lines[2][2] = 7;
lines[2][3] = 3;

lines[3][0] = 1;
lines[3][1] = 5;
lines[3][2] = 6;
lines[3][3] = 2;

lines[4][0] = 0;
lines[4][1] = 4;
lines[4][2] = 5;
lines[4][3] = 1;

lines[5][0] = 3;
lines[5][1] = 7;
lines[5][2] = 6;
lines[5][3] = 2;

for(int i = 0; i < 8; i++) {
center.x += points.x;
center.y += points.y;
center.z += points.z;
}
center.x /= 8;
center.y /= 8;
center.z /= 8;

while(true){
RotatePoints();
canvas.repaint();
try{
Thread.sleep(16);
} catch(InterruptedException e) {}
}
}

public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(new Color(125, 23, 238));
g.fillRect(0, 0, 25, 25);
LINE line = new LINE();
for(int x = 0; x < 6; x++){
for(int y = 0; y < 4; y++){
int a = lines[x][y], b = lines[x][(y + 1) % 4];
line.Calc(draw[a], draw);
for(; line.start < line.end; line.start += 1.0){
double w = line.slope * line.start + line.steps;
if(line.rev){
g.drawRect((int)w, (int)line.start, 1, 1);
} else {
g.drawRect((int)line.start, (int)w, 1, 1);
}
}
}
}

}

public static void RotatePoints(){
rotation.x += 0.1;
rotation.y += 0.5;
rotation.z += 0.25;

double sx = Math.sin(Math.toRadians(rotation.x)), sy = Math.sin(Math.toRadians(rotation.y)), sz = Math.sin(Math.toRadians(rotation.z));
double cx = Math.cos(Math.toRadians(rotation.x)), cy = Math.cos(Math.toRadians(rotation.y)), cz = Math.cos(Math.toRadians(rotation.z));

for(int i = 0; i < 8; i++){
Point3D spot = points;

draw.y = (cx * (spot.y - center.y) - sx * (spot.z - center.z)) + center.y;
draw.z = (sx * (spot.y - center.y) + cx * (spot.z - center.z)) + center.z;
spot = draw;// new Point3D(draw.x, draw.y, draw.z);
draw[i].x = (cy * (spot.x - center.x) - sy * (spot.z - center.z)) + center.x;
draw[i].z = (sy * (spot.x - center.x) + cy * (spot.z - center.z)) + center.z;
spot = draw[i]; //new Point3D(draw[i].x, draw[i].y, draw[i].z);
draw[i].x = (cz * (spot.x - center.x) - sz * (spot.y - center.y)) + center.x;
draw[i].y = (cz * (spot.y - center.y) + sz * (spot.x - center.x)) + center.y;

}
}

}


Подробнее здесь: https://stackoverflow.com/questions/783 ... -correctly
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»