修复旋转3D对象的Perl代码

时间:2013-05-16 15:24:20

标签: perl 3d

我使用net中的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;
}

但是出了点问题。对象大小/形式无法保持不变。我的数学并不是很好理解为什么。我甚至不确定我需要+=还是=

2 个答案:

答案 0 :(得分:1)

Thx amon。正如所建议的那样:

#@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点旋转然后转换回来?

答案 1 :(得分:-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]]);