当用户按住 LMB 并移动鼠标时,立方体会旋转。我使用假人作为一种“锚”,以便相机保持在同一个位置,但物体旋转,所以可以看到所有侧面旋转对象(这是一个立方体)。问题是物体旋转后,它的 x 和 y 保持不变,因此相同的运动会从相机的角度产生不同的效果。例如,如果我向上旋转 180 度(y),则 x 轴的旋转是镜像的,因为向左移动鼠标会沿相反的方向旋转,就像在 180 度旋转之前一样
这是我的代码:
表单创建:
procedure TForm2.Form3DCreate(Sender: TObject);
begin
Xf := 0;
Yf := 0;
Xi := 0;
Yi := 0;
Xd := 0;
Yd := 0;
end;
开始按钮:
procedure TForm2.btnStartClick(Sender: TObject);
begin
layerStart.Visible := False;
Controller := TController.create(Form2,10);
Camera1 := TCamera.Create(Controller.getAnchor);
Camera1.Parent := Controller.getAnchor;
Anchor := Controller.getAnchor;
Timer1.Enabled := True;
end;
创建对象和“锚”:
Type
tController = class
private
cubeArray : Array[1..10,1..10,1..10] of TCube;
fCubeCount, fHalf : integer;
fForm : TForm3D;
bigCube : tDummy;
public
constructor create(Form : TForm3D; cubeCount :integer);
function getAnchor : tDummy;
end;
implementation
{ tController }
constructor tController.create(Form: TForm3D; cubeCount: integer); //cubeCount Max 10, min 1
var
x, y, z : Integer;
begin
fCubeCount := cubeCount;
fForm := Form;
fHalf := cubeCount div 2;
bigCube := TDummy.Create(Form);
With bigCube do
begin
Visible := True;
Position.X := 0;
Position.Y := 0;
Position.Z := 0;
Parent := Form;
end;
for x := 1 to fCubeCount do
begin
for y := 1 to fCubeCount do
begin
for z := 1 to fCubeCount do
begin
CubeArray[x,y,z] := TCube.Create(bigCube);
With CubeArray[x,y,z] do
begin
Visible := True;
Width := 0.5;
Height := 0.5;
Depth := 0.5;
Position.X := x - 0.5 - fHalf;
Position.Y := y - 0.5 - fHalf;
Position.Z := z - 0.5 - fHalf;
Parent := bigCube;
end;
end;
end;
end;
end;
function tController.getAnchor: TDummy;
begin
result := bigCube;
end;
end.
定时器:
procedure TForm2.Timer1Timer(Sender: TObject);
begin
// X on Form to Left = 60; X on form to right = 1280
while GetAsyncKeyState(VK_LBUTTON) = -32768 do
begin
Xi := Screen.MousePos.X;
Yi := Screen.MousePos.Y;
Sleep(1);
Xf := Screen.MousePos.X;
Yf := Screen.MousePos.Y;
Xd := (Xi-Xf);
Yd := (Yi-Yf)*-1;// *-1 for compliance with Cartesian plane logic
Xd := (Xd / 1220)*360*10; //COnverting from X units to degrees, *10 for more rotation per amount moved by mouse
Yd := (Yd / 1220)*360*10;
Anchor.RotationAngle.Y := Anchor.RotationAngle.Y + Xd;
Anchor.RotationAngle.X := Anchor.RotationAngle.X + Yd;
Application.ProcessMessages;
end;
end;
我要旋转的对象是由所有较小的立方体组成的立方体。据我所知,这个问题源于锚在旋转后相对于立方体保持不变的事实,即旋转的原点随着旋转的对象移动。我将如何解决这个问题?