Creating Random Colored Sphere with Panda3D

  • Share this:

Code introduction


This function uses the Panda3D library to create a random colored sphere with a specified radius and color.


Technology Stack : Panda3D, GeomNode, GeomVertexFormat, GeomVertexWriter, Geom, LVector3, LColor

Code Type : 3 D graphics creation

Code Difficulty : Intermediate


                
                    
def create_random_sphere(radius=1, color=(1, 0, 0, 1)):
    """
    This function creates a random sphere with a given radius and color.
    """
    from panda3d.core import GeomNode
    from panda3d.core import GeomVertexFormat
    from panda3d.core import GeomVertexWriter
    from panda3d.core import Geom
    from panda3d.core import LVector3
    from panda3d.core import LColor

    # Define the format of the vertices in the geometry
    vertex_format = GeomVertexFormat.getV3c4()

    # Create a new geometry
    geom = Geom(vertex_format)

    # Create a vertex writer for the x, y, z coordinates
    x = GeomVertexWriter(geom, "vertex", 3)
    # Create a vertex writer for the color
    c = GeomVertexWriter(geom, "color", 4)

    # Define the number of vertices for the sphere
    num_vertices = 36

    # Generate vertices for the sphere
    for i in range(num_vertices):
        angle = i * 2 * 3.14159 / num_vertices
        x.setValue(LVector3(radius * math.sin(angle), radius * math.cos(angle), 0))
        c.setValue(LColor(*color))

    # Create a geom node from the geometry
    geom_node = GeomNode('sphere')
    geom_node.addGeom(geom)

    return geom_node