1
$\begingroup$

I suck at programming but am trying to rotate an object a specific way. The line own.localOrientation=mathutils.Matrix(x, y, z) is giving me an error:

TypeError: Matrix(): expects no args or a single arg containing 2-4 numeric sequences

The most likely problem is I'm formatting the matrix wrong when I go to add it but the error isn't really helping me figure out exactly what I've done wrong.

$\endgroup$
0

2 Answers 2

5
$\begingroup$

Euler rotation as a matrix

Would imagine that what you want for x, y, z is an Euler rotation.

The KX_GameObject.localOrientation expects a 3x3 matrix, an Euler or a Quaternion.

euler_rotation = mathutils.Euler((x, y, z), 'XYZ') # XYZ is default
# 3 x 3 rotation matrix
R = euler_rotation.to_matrix()

this is the equivalent of

Rx = mathutils.Matrix.Rotation(x, 3, 'X')
Ry = mathutils.Matrix.Rotation(y, 3, 'Y')
Rz = mathutils.Matrix.Rotation(z, 3, 'Z')
R = Rz * Ry * Rx # ( XYZ order)

Can either set your local orientation to this matrix, or to rotate by it

own.localOrientation = R * own.localOrientation

remember all rotations need to be in radians. x = math.radians(45)

Putting it together in game engine, the following in a text block named rot.py

from mathutils import Euler
from math import radians
x = y = z = radians(5)
R = Euler((x, y, z)).to_matrix()

def main(cont):
    own = cont.owner
    # color vector xyzw  ~ rgba
    own.localOrientation = R * own.localOrientation

Assign to the left mouse click. Now on every click the owner is rotated 5 degrees on each axis each click

enter image description here

$\endgroup$
4
  • $\begingroup$ It doesn't seem to like the 'XYZ' portion. Says invalid syntax. Removing it then says mathutils.Euler() takes at most 2 arguments (3 given) $\endgroup$
    – ruckus
    Mar 12, 2018 at 17:43
  • $\begingroup$ @Scalia Notice it's Euler( (x, y, z) ) not Euler(x, y, z) The first has one argument the tuple (x, y, z) "and is right" the second three, x, y and z "wrong" Euler((x, y, z), 'XYZ') has two arguments and is "right" $\endgroup$
    – batFINGER
    Mar 13, 2018 at 10:27
  • $\begingroup$ R = Rz @ Ry @ Rx # ( XYZ order) #inversed order $\endgroup$ Jan 23, 2021 at 23:31
  • $\begingroup$ Thankyou edited. $\endgroup$
    – batFINGER
    Jan 24, 2021 at 2:10
1
$\begingroup$

To create a rotation matrix with angle try:

mathutils.Matrix.Rotation(radians(90.0), 4, 'X')

as mentioned in the Blender API

$\endgroup$
2
  • $\begingroup$ ValueError: Matrix.Rotation(): can only return a 2x2 3x3 or 4x4 matrix $\endgroup$
    – ruckus
    Mar 12, 2018 at 18:11
  • 1
    $\begingroup$ What is the code belonging to this error? $\endgroup$
    – Monster
    Mar 13, 2018 at 5:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .