2

我使用来自网络的 C++ 示例编写了这段代码,以在 3D 中旋转我的点集。

#@matrix is points and their 3D coordinates.
@rotated_matrix = rotate_l(\@matrix, 0);

sub rotate_l {
  my $ref = $_[0];
  my $x = 0;
  my $step = 1;

  #if rotx
  if ($_[1] == 0) {
    while ($$ref[$x][0]) {
      $$ref[$x][1] += ($$ref[$x][1]*cos($step) - $$ref[$x][2]*sin($step));
      $$ref[$x][2] += ($$ref[$x][1]*sin($step) + $$ref[$x][2]*cos($step));
      $x++;
    }
  }

  #if roty
  if ($_[1] == 1) {
    while ($$ref[$x][0]) {
      $$ref[$x][0] += ( $$ref[$x][0]*cos($step) + $$ref[$x][2]*sin($step));
      $$ref[$x][2] += (-$$ref[$x][0]*sin($step) + $$ref[$x][2]*cos($step));
      $x++;
    }
  }


  #if rotz
  if ($_[1] == 2) {
    while ($$ref[$x][0]) {
      $$ref[$x][0] += ($$ref[$x][0]*cos($step) - $$ref[$x][1]*sin($step));
      $$ref[$x][1] += ($$ref[$x][0]*sin($step) + $$ref[$x][1]*cos($step));
      $x++;
    }
  }

 return @$ref;
}

但有些不对劲。对象大小/形式无法保持不变。而且我的数学不太好理解为什么。我什至不确定我需要+=还是=

4

2 回答 2

1

谢谢阿蒙。正如所建议的那样:

#@matrix is points and their 3D coordinates.
@rotated_matrix = rotate_l(\@matrix, 0);

sub rotate_l {
  my $ref = $_[0];
  my $x = 0;
  my $step = pi;

  #if rotx
  if ($_[1] == 0) {
    while ($$ref[$x][0]) {
      $$ref[$x][1] = ($$ref[$x][1]*cos($step) - $$ref[$x][2]*sin($step));
      $$ref[$x][2] = ($$ref[$x][1]*sin($step) + $$ref[$x][2]*cos($step));
      $x++;
    }
  }

  #if roty
  if ($_[1] == 1) {
    while ($$ref[$x][0]) {
      $$ref[$x][0] = ( $$ref[$x][0]*cos($step) + $$ref[$x][2]*sin($step));
      $$ref[$x][2] = (-$$ref[$x][0]*sin($step) + $$ref[$x][2]*cos($step));
      $x++;
    }
  }


  #if rotz
  if ($_[1] == 2) {
    while ($$ref[$x][0]) {
      $$ref[$x][0] = ($$ref[$x][0]*cos($step) - $$ref[$x][1]*sin($step));
      $$ref[$x][1] = ($$ref[$x][0]*sin($step) + $$ref[$x][1]*cos($step));
      $x++;
    }
  }

 return @$ref;
}

如果我不需要围绕 (0,0,0) 旋转,而是相对于其他点旋转,最好的方法是平移到 0 点旋转然后再平移回来?

于 2013-05-16T17:00:08.550 回答
-1

就像我建议你做的事情的一个例子:

#! /usr/bin/env perl
use common::sense;
use YAML 'Dump';

sub translate {
  my ($deltaX, $deltaY) = @{pop()};  # <-- don't mind this.
  for (@_) {    # <--- this is the important part
    $_->[0] += $deltaX;
    $_->[1] += $deltaY;
  }
  @_
}

my @points = ([0, 1], [0, -1], [-1, 0], [1, 0]);

print Dump([translate @points, [2, 2]]);

my $box = \@points;

print Dump([translate @$box, [5, 0]]);
于 2013-05-16T16:39:20.747 回答