2013-05-16 52 views
2

我用网络中的C++示例编写了这段代码,以旋转3D中的一组点。修复旋转3D对象Perl代码

#@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; 
} 

但是有什么不对。对象大小/形式不能保持不变。我的数学不是很好理解为什么。我甚至不确定我需要+==

+0

C++示例是否工作? – choroba

+1

我强烈怀疑'$ step'要乘以'2 pi',并且所有'+ ='都将被替换为'='。然后它几乎奏效。 – amon

+0

我发誓,花了一分多时间才意识到这个页面上有Perl代码。我正要在一个评论中提问:“这个问题与Perl有什么关系?你想把这个C++翻译成Perl吗?你试过了什么?” –

回答

-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]]); 
1

THX阿蒙。作为建议这个工程:

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