# Script for hexagonal distribution

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.

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)

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:

• The cube is defined by the xyz1 and xyz2 parameters. In the sample invocation it is [-5,-5,-5], [5,5,5]. Jan 17, 2017 at 0:54