Randomly switch object positions

The following function comes in handy when e.g. populating parking lots with many different cars. This way you only need to use one type of car for each section (and dummy helpers as placeholders for empty ones) and the randomness is then achieved by using this function:
fn switchObjectsPositonsRandomly obj_array =
    if isKindOf obj_array ObjectSet OR isKindOf obj_array PathName do
        obj_array = obj_array as array

    if classOf obj_array != Array OR obj_array.count < 2 do
        return false

    objs_transforms = for o in obj_array collect o.transform
    with redraw off for o in obj_array do
        local objs_transforms_index = (random 1 objs_transforms.count)
        local random_objs_transforms = objs_transforms[objs_transforms_index]
        local new_transform = transMatrix random_objs_transforms.pos

        preScale new_transform o.transform.scalePart
        preRotate new_transform random_objs_transforms.rotationPart
        o.transform = new_transform
        deleteItem objs_transforms objs_transforms_index
USAGE: All you need to do here is pass it an array of objects and evaluate it:

switchObjectsPositonsRandomly selection
switchObjectsPositonsRandomly $car_*

Switched positions

LIMITATIONS: Doesn't really support non-uniform scale - and of course, the objects' pivots should be  placed consistently (for example in the middle of the object on zero Z coordinate (obj.pivot = [,, selection.min.z])), otherwise you can get unexpected results.

DISCLAIMER: All scripts and snippets are provided as is under Creative Commons Zero (public domain, no restrictions) license. The author and this blog cannot be held liable for any loss caused as a result of inaccuracy or error within these web pages. Use at your own risk.

This Post needs Your Comment!

Return to top