2
$\begingroup$

I wrote the following Python, which is not ideal for me as it seems to be moving on the YZ axis

import bpy
import random

Num_Min = -0.01
Num_Max = 0.01

Target_Objects = bpy.context.selected_objects
for Target_Obj in Target_Objects:
 Target_Obj.location[1] = random.uniform(Num_Min, Num_Max)
 Target_Obj.location[2] = random.uniform(Num_Min, Num_Max)

I want to move to the XY axis. Also, I want to control the range that can be moved by setting "Min & Max".

Thank you.

$\endgroup$
4
$\begingroup$

Not sure what do you mean XY axis, But you might misunderstand the subscription for array in python. They should start at 0 not 1. eg. x = [3,6,9]; x[0] # is 3. The Object.location (Vector) stand for [X,Y,Z] So you might need to use location[0], location[1] instead.

Instead of using number to retrieve axis, ones should use properties to get the axis for clearance. eg. location.x = 1.0; location.y = 2.0

import bpy
import random

constrain = (-0.01, 0.01) # I prefer to use tuple for min, max value

for target_obj in bpy.context.selected_objects: # PEP8 recommend to use lower snake case
  target_obj.location.x = random.uniform(*constrain) # And unpack them using *
  target_obj.location.y = random.uniform(*constrain)
  continue
  # Another approach
  target_obj.location.xy = (random.uniform(*constrain), random.uniform(*constrain))
  # There can be called and manipulated by combination as well
| improve this answer | |
$\endgroup$
  • $\begingroup$ Sorry. The z-axis means you want to fix it. But this is what I think is the ideal behavior! And it's a very straightforward code! Thank you so much! $\endgroup$ – InamuraJIN Jul 14 at 13:20
  • $\begingroup$ I'm sorry. Just one more question. What do I do if I want to specify separate numbers for the X and Y axes? Example. ``` Xconstrain = (-10, -12) Yconstrain = (-1, 2) for target_obj in bpy.context.selected_objects: target_obj.location.x = random.uniform(*constrain) target_obj.location.y = random.uniform(*constrain) ``` $\endgroup$ – InamuraJIN Jul 14 at 13:31
  • $\begingroup$ then unpack them again using * sign: target_obj.location.xy = (random.uniform(*Xconstrain), random.uniform(*Yconstrain)). If you are not sure what code will do the effect you want, you can use the python interactive console inside Blender $\endgroup$ – HikariTW Jul 15 at 0:28
  • $\begingroup$ I don't know how to merge those codes together... $\endgroup$ – InamuraJIN Jul 15 at 2:23
  • 1
    $\begingroup$ That's for sure. But in this case, it seems to have worked. imgur.com/4BJKHs5 Thank you!! $\endgroup$ – InamuraJIN Jul 15 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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