Page 1 of 1

Vector Rotation

Posted: Sat Oct 12, 2013 5:14 pm
by IMP1
I'm trying to make my own vector module, and for the most part it works (as far as I know), but in trying to add rotation I'm getting unexpected results.
I'm not 100% sure whether the results are right, and my expectations are wrong, or vice versa.

I'm rotating a 3D vector by an angle 'a', and then rotating it by '-a'. But it doesn't end up the same as it started.

The vector rotation code is on lines 166 through to 181.
I know and don't mind that it assumes the vector is 3D.

Can anyone please help?

Re: Vector Rotation

Posted: Sat Oct 12, 2013 7:24 pm
by Xgoff
precision issues? (seems kind of excessive though...)

Re: Vector Rotation

Posted: Sat Oct 12, 2013 7:31 pm
by chezrom
The problem is due to modification of origin vector during computation (origin vector = result vector).

For the rotation around x-axis, the formula must be :
x' = x
y' = cos * y + sin *z
z' = cos * z - sin * y

Or in fact you do y = ...., so you change y value for the z' computation and the the z result is false.

You can rewrite you code as this :

Code: Select all

function Vector:rotate(a, b, c)
    local outcome = self:copy()
	local x,y,z

    -- x-axis
	y,z = outcome.y, outcome.z
    outcome.y = y * math.cos(a) + z * math.sin(a)
    outcome.z = z * math.cos(a) - y * math.sin(a)

    -- y-axis
	x,z = outcome.x, outcome.z
    outcome.x = x * math.cos(b) - z * math.sin(b)
    outcome.z = z * math.cos(b) + x * math.sin(b)

    -- z-axis
	x,y = outcome.x,outcome.y
    outcome.x = x * math.cos(c) + y * math.sin(c)
    outcome.y = y * math.cos(c) - x * math.sin(c)
    return outcome

Re: Vector Rotation

Posted: Sun Oct 13, 2013 12:43 pm
by IMP1
Ah, of course, that makes perfect sense.
Thank you very much for pointing out my mistake.