Creating a Panda3D Sphere with Custom Radius and Color

  • Share this:

Code introduction


This function creates a sphere with a specified radius and color. The sphere is composed of line segments and is rendered using Panda3D's geometry node.


Technology Stack : Panda3D

Code Type : Panda3 D 3 D graphics programming

Code Difficulty : Intermediate


                
                    
def create_random_sphere(radius, color=(1, 1, 1)):
    from panda3d.core import NodePath
    from panda3d.core import GeomNode
    from panda3d.core import Geom
    from panda3d.core import GeomVertexFormat
    from panda3d.core import GeomVertexWriter
    from panda3d.core import BitMask32
    from panda3d.core import LineNode
    from panda3d.core import LineSegs
    
    # Create a sphere
    sphere = LineSegs()
    sphere.set_num_segments(32)
    sphere.set_radius(radius)
    sphere.set_color(*color)
    sphere_node = NodePath(sphere.create())
    
    # Create a GeomNode for the sphere
    vertex_format = GeomVertexFormat.get_default()
    geom = Geom(vertex_format)
    vertex_writer = GeomVertexWriter(geom, "vertex")
    
    # Add vertices to the geom
    for i in range(sphere.getNumVertices()):
        vertex_writer.add_data(sphere.get_vertex(i))
    
    geom_node = GeomNode("sphere_geom")
    geom_node.addGeom(geom)
    sphere_node.reparentTo(geom_node)
    
    return geom_node                
              
Tags: