1
class quaternion:
    __slots__ = ("x", "y", "z", "w")

    def __init__(self, x: float, y: float, z: float, w: float):
        self.x = x
        self.y = y
        self.z = z
        self.w = w

    def rotate(self, x: float, y: float, z: float):
        # Correctly bump self.x, self.y, self.z, self.w with the provided radians

I'm implementing quaternion rotations in my code for cases where euler vectors are the lesser option. I have functions to set them and retrieve the forward / right / up vectors, but can't find good examples of how to apply a rotation. Unlike eulers I can't just bump x, y, z, w individually: Each modification to one axis must reflect on the others, and I need quaternions to rotate along their selves so for example if I want to bump it by a rotation of -0.1 on the X axis I want the object to rotate to its own left considering its pitch and roll.

1
  • Obvious to take from tested existing code
    – minorlogic
    Commented Jul 7 at 13:01

1 Answer 1

0

Found a solution that works great. What I wanted was quaternion multiplication: I can convert both the base rotation and offset from euler to quaternion, after which multiplying the two quaternions offers the desired result.

class quaternion:
    __slots__ = ("x", "y", "z", "w")

    def __init__(self, x: float, y: float, z: float, w: float):
        self.x = x
        self.y = y
        self.z = z
        self.w = w

    def multiply(self, other):
        x = other.x * self.w + other.y * self.z - other.z * self.y + other.w * self.x
        y = other.x * self.z + other.y * self.w + other.z * self.x + other.w * self.y
        z = other.x * self.y - other.y * self.x + other.z * self.w + other.w * self.z
        w = other.x * self.x - other.y * self.y - other.z * self.z + other.w * self.w

        return quaternion(x, y, z, w)
2
  • 1
    Technically, rotation is done via p q p.comjugate() assuming that p is normalized, and rotation is by 2 w if p is ( sin( w) (x,y,z), cos(w) ) . So what is it that you want to rotate? Commented Jul 8 at 8:43
  • 1
    Here would be an example. Commented Jul 9 at 8:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.