1
$\begingroup$

I need to create a cube that contains spheres of the same diameter with hexagonal distribution, I know that with particles we can do it, but for me I want to create with python script, the data are: the number of sphere and their radius, Can you create this script.

$\endgroup$

1 Answer 1

2
$\begingroup$

First create a prototype of your cannonball and name it "prototype".

Here is code which will stack cannonballs for you:

import bpy
from math import *

def construct_cannonball(mesh, x,y,z):
    scn = bpy.context.scene

    obj = bpy.data.objects.new("ball", mesh)
    scn.objects.link(obj)

    obj.location = [x,y,z]


def mission1(mesh, r, xyz1, xyz2, construct_cannonball=construct_cannonball):

    dx = 2*r
    dy = sqrt(0.75)*dx

    dz = sqrt(2/3)*dx   # thank you, CRC Concise Encyclopedia of Mathematics

    w = 0
    z=xyz1[2]
    while z<xyz2[2]:

        v=0
        y=xyz1[1]
        if 1==w%2:
            y += dx/2 * tan(pi/6)
        while y < xyz2[1]:
            x = xyz1[0]
            if 1==w%2:
                if 1==v%2:
                    x -= dx/2 / cos(pi/6)
                else:
                    x += dx/2 / cos(pi/6)
            if 1 == v%2:
                x += dx/2
            while x < xyz2[0]:
                construct_cannonball(mesh, x,y,z)
                x += dx

            y += dy
            v+=1

        z += dz
        w += 1


def purge(scn, prefix):
    for obj in scn.objects:
        if obj.name[0:len(prefix)] == prefix:
            obj.name = "discard"
            scn.objects.unlink(obj)

purge(bpy.context.scene, "ball")

mission1(bpy.data.objects['prototype'].data,
         1, [-5,-5,-5], [5,5,5])

You can see a copy of the code at http://web.purplefrog.com/~thoth/blender/python-cookbook/cannonball-packing.html

$\endgroup$
4
  • $\begingroup$ In line 15: mission1(bpy.data.objects['prototype'].data, ... , I have an error $\endgroup$
    – saded
    Jan 12, 2017 at 19:03
  • $\begingroup$ Yeah, I edited the answer to mention that you need an object in your scene named "prototype" to be your sample cannonball. $\endgroup$
    – Mutant Bob
    Jan 12, 2017 at 19:05
  • $\begingroup$ How to add the cube that contains this distribution $\endgroup$
    – saded
    Jan 15, 2017 at 10:36
  • $\begingroup$ The cube is defined by the xyz1 and xyz2 parameters. In the sample invocation it is [-5,-5,-5], [5,5,5]. $\endgroup$
    – Mutant Bob
    Jan 17, 2017 at 0:54

You must log in to answer this question.

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