XGen - How to convert a 2D vector to degrees ranging from 0 to 360?

XGen - How to convert a 2D vector to degrees ranging from 0 to 360?

dkrelina
Advocate Advocate
1,124 Views
1 Reply
Message 1 of 2

XGen - How to convert a 2D vector to degrees ranging from 0 to 360?

dkrelina
Advocate
Advocate
Hi,
 
I'm working on an XGen expression that sets instance rotation based on a flow map (the red and green channels of the flow map define the vector).
 
Here's an example of a flow map made using FlowMap Painter.
0_oZW7G8ZEF2wm_1JZ.png
 
I am using the XGen function atand() to convert the vector to degrees. I normalize the red and green channels ($x and $y) to fit the range range of -1 to 1 and go atand($y/$x). This does the trick but I'm noticing a few issues...
  1. This function only returns values between positive and negative 90, not full 360.
  2. When $x is zero, we have an error.
I had to write a few if statements to handle these exceptions. Here is the full script.
# define variables
$flowMap=map('${DESC}/paintmaps/aboutN2');#3dpaint,128.0
$rotationOffset = 90.0000;

# get x and y values from r and g channels
$x = ($flowMap[0] * 2) - 1;
$y = ($flowMap[1] * 2) - 1;

# make sure that there are no zero values
if ($x==0){
    $x = 1e-08;
}
if ($y==0){
    $y = 1e-08;
}

# define offset for negative values
if ($x>0 && $y<=0){
    $a = 180;
}
else if($x<=0 && $y<=0){
    $a = 180;
}
else if($x<=0 && $y>0){
    $a = 360;
}
else {
    $a = 0;
}

# convert vector to degrees and do offset
$deg = atand($y/$x);
$val = $a + $deg + $rotationOffset;
$val
 
My question...
 
Is there a more elegant way to convert a 2D vector to degrees that ranges from 0 to 360? Could this be done in fewer lines with different function(s)?
0 Likes
Accepted solutions (1)
1,125 Views
1 Reply
Reply (1)
Message 2 of 2

tkaap2
Autodesk
Autodesk
Accepted solution

If you're looking for an elegant way to adjust quadrants like that, look at atan2().  It might be a personal preference as to which adjustment you want to make, but the atan2(x,y) expression in most math programs is intended to make that quadrant adjustment for you.  

 

But obviously that won't return in degrees, so you'd need to do that adjustment yourself, but it might make a cleaner script.