I'm procedurally placing objects (XY dimension only) around a central object, with some randomness to their distance/angle relative to the central object. Occasionally, this results in overlap between these placed objects.
To detect and remedy this, I'm using a cheap and easy method, of simply finding the distance between these objects, and comparing it to a known value, based on the size of the object being placed. If the objects are too close, i want to move them both directly away from each other. From the blender documentation, the operator "push_pull" looks perfect for this, and works just as I want to when using the GUI. Unfortunately, I cannot get it working using BPY python scripting. This is a demo version of what I'm trying to do:
import bpy
from math import sqrt
def dist(a, b):
dx = a.location[0] - b.location[0]
dy = a.location[1] - b.location[1]
return sqrt(dx*dx + dy*dy)
min_dist = 4 # minimum centre-to-centre distance for follower placement (prevent overlap)
bpy.ops.mesh.primitive_cube_add(
location=(0, 0, 0), scale=(4, 4, 1)
)
Cube1 = bpy.context.object
Cube1.data.name = "C1"
Cube1.name = "C1"
bpy.ops.mesh.primitive_cube_add(
location=(1, 1, 0), scale=(4, 4, 1)
)
Cube2 = bpy.context.object
Cube2.data.name = "C2"
Cube2.name = "C2"
cubes_distance = dist(Cube1, Cube2)
if cubes_distance < min_dist:
print("TOO CLOSE")
bpy.context.view_layer.objects.active = None
Cube1.select_set(True)
Cube2.select_set(True)
bpy.ops.transform.push_pull(value=(min_dist-cubes_distance))
bpy.context.view_layer.objects.active = None
Is this a problem of object selection / context? When I run this script in GUI, it doesnt return any errors, and the two cubes are selected in the viewport, but no push is applied