示例#1
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-3, 0, 4)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(0, 0, 0)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Slider
        frameA = TransformState.make_pos_hpr(LPoint3(2, 0, 0),
                                             LVector3(0, 0, 45))
        frameB = TransformState.make_pos_hpr(LPoint3(0, -3, 0),
                                             LVector3(0, 0, 0))

        slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
        slider.set_debug_draw_size(2.0)
        slider.set_lower_linear_limit(0)
        slider.set_upper_linear_limit(6)
        slider.set_lower_angular_limit(-60)
        slider.set_upper_angular_limit(60)
        self.world.attach(slider)
示例#2
0
def NormalizedSquarePatchAABB(radius,
                              x0,
                              y0,
                              x1,
                              y1,
                              offset=None,
                              x_inverted=False,
                              y_inverted=False,
                              xy_swap=False):
    a = NormalizedSquarePatchPoint(radius, 0, 0, x0, y0, x1, y1, offset,
                                   x_inverted, y_inverted, xy_swap)
    b = NormalizedSquarePatchPoint(radius, 1, 0, x0, y0, x1, y1, offset,
                                   x_inverted, y_inverted, xy_swap)
    c = NormalizedSquarePatchPoint(radius, 1, 1, x0, y0, x1, y1, offset,
                                   x_inverted, y_inverted, xy_swap)
    d = NormalizedSquarePatchPoint(radius, 0, 1, x0, y0, x1, y1, offset,
                                   x_inverted, y_inverted, xy_swap)
    m = NormalizedSquarePatchPoint(radius, 0.5, 0.5, x0, y0, x1, y1, offset,
                                   x_inverted, y_inverted, xy_swap)
    x_min = min(a[0], b[0], c[0], d[0], m[0])
    y_min = min(a[1], b[1], c[1], d[1], m[1])
    z_min = min(a[2], b[2], c[2], d[2], m[2])
    x_max = max(a[0], b[0], c[0], d[0], m[0])
    y_max = max(a[1], b[1], c[1], d[1], m[1])
    z_max = max(a[2], b[2], c[2], d[2], m[2])
    return BoundingBox(LPoint3(x_min, y_min, z_min),
                       LPoint3(x_max, y_max, z_max))
示例#3
0
    def rebuild(self, view_size):
        self.view_size = view_size
        props = base.win.getProperties()
        y = props.getYSize()
        pxm = float(y) / self.view_size
        hsize = 12 / pxm
        vsize = 40 / pxm
        #print(hsize, vsize)
        cm = CardMaker('card')
        cm.setFrame(LPoint3(-hsize, 0, 0), LPoint3(hsize, 0, 0),
                    LPoint3(hsize, vsize, 0), LPoint3(-hsize, vsize, 0))

        for n in self.nodes:
            n.removeNode()

        self.nodes = []
        for m in self.markers:
            node = NodePath(cm.generate())
            node.setTexture(self.icon, 1)
            node.setTransparency(TransparencyAttrib.MAlpha)
            node.setDepthTest(False)
            node.setDepthWrite(False)
            node.setBin("unsorted", 1)
            ned = m['ned']
            node.setPos(ned[1], ned[0], 0)
            node.reparentTo(self.render)
            self.nodes.append(node)
示例#4
0
    def update_shader_shape(self, shape, appearance):
        planet = self.parameters.planet
        factor = 1.0 / shape.owner.scene_scale_factor
        inner_radius = self.parameters.planet_radius

        #TODO: We should get the oblateness correctly
        planet_scale = self.parameters.planet.surface.get_scale()
        descale = LMatrix4.scale_mat(inner_radius / planet_scale[0], inner_radius / planet_scale[1], inner_radius / planet_scale[2])
        rotation_mat = LMatrix4()
        orientation = LQuaternion(*shape.owner.scene_orientation)
        orientation.extract_to_matrix(rotation_mat)
        rotation_mat_inv = LMatrix4()
        rotation_mat_inv.invert_from(rotation_mat)
        descale_mat = rotation_mat_inv * descale * rotation_mat
        pos = planet.rel_position
        scaled_pos = descale_mat.xform_point(LPoint3(*pos))
        star_pos = planet.star._local_position - planet._local_position
        scaled_star_pos = descale_mat.xform_point(LPoint3(*star_pos))
        scaled_star_pos.normalize()
        camera_height = scaled_pos.length()
        shape.instance.setShaderInput("v3OriginPos", pos)
        shape.instance.setShaderInput("v3CameraPos", -scaled_pos)

        shape.instance.setShaderInput("fCameraHeight", camera_height)
        shape.instance.setShaderInput("fCameraHeight2", camera_height * camera_height)

        shape.instance.setShaderInput("v3LightPos", scaled_star_pos)
        shape.instance.setShaderInput("model_scale", factor)
        shape.instance.setShaderInput("atm_descale", descale_mat)
示例#5
0
def halfSphereAABB(height, positive, offset):
    if positive:
        min_points = LPoint3(-1, 0 - offset, -1)
        max_points = LPoint3(1, 1 - offset, 1)
    else:
        min_points = LPoint3(-1, offset - 1, -1)
        max_points = LPoint3(1, offset, 1)
    return BoundingBox(min_points, max_points)
 def __estimateSize__(self):
   minp = LPoint3.zero()
   maxp = LPoint3.zero()
   size = Vec3.zero()
   if self.calcTightBounds(minp,maxp):
     size = maxp - minp
     
   return size 
示例#7
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-2, 0, 1)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(2, 0, 1)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Hinge
        pivotA = LPoint3(2, 0, 0)
        pivotB = LPoint3(-4, 0, 0)
        axisA = LVector3(0, 0, 1)
        axisB = LVector3(0, 0, 1)

        hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA,
                                      axisB, True)
        hinge.set_debug_draw_size(2.0)
        hinge.set_limit(-90, 120, softness=0.9, bias=0.3, relaxation=1.0)
        self.world.attach(hinge)
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-2, 0, 4)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(0, 0, 0)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Cone
        frameA = TransformState.make_pos_hpr(LPoint3(0, 0, -2),
                                             LVector3(0, 0, 90))
        frameB = TransformState.make_pos_hpr(LPoint3(-5, 0, 0),
                                             LVector3(0, 0, 0))

        cone = BulletConeTwistConstraint(bodyA, bodyB, frameA, frameB)
        cone.set_debug_draw_size(2.0)
        cone.set_limit(30, 45, 170, softness=1.0, bias=0.3, relaxation=8.0)
        self.world.attach(cone)
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-1, 0, 4)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.node().setLinearDamping(0.6)
        bodyNP.node().setAngularDamping(0.6)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(2, 0, 0)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Spherical Constraint
        pivotA = LPoint3(2, 0, 0)
        pivotB = LPoint3(0, 0, 4)

        joint = BulletSphericalConstraint(bodyA, bodyB, pivotA, pivotB)
        joint.set_debug_draw_size(2.0)
        self.world.attach(joint)
示例#10
0
 def spawnAliens(self):
     self.aliens = []
     leftmost = -17
     highest = 13
     for i in range(11):
         self.aliens.append([])
         self.aliens[i].append(Alien30pt(position=LPoint3(leftmost + 2.5 * i, 0, highest)))
         self.aliens[i].append(Alien20pt(position=LPoint3(leftmost + 2.5 * i, 0, highest - 2.5)))
         self.aliens[i].append(Alien20pt(position=LPoint3(leftmost + 2.5 * i, 0, highest - 5.0)))
         self.aliens[i].append(Alien10pt(position=LPoint3(leftmost + 2.5 * i, 0, highest - 7.5)))
         self.aliens[i].append(Alien10pt(position=LPoint3(leftmost + 2.5 * i, 0, highest - 10.0)))
示例#11
0
    def __init__(self):
        ShowBase.__init__(self)
        self.disableMouse()
        self.setBackgroundColor((0, 0, 0, 1))
        # load the background
        self.bg = loadObject("Game_Background.png", pos=LPoint3(0,0,3), scale=146, depth=200, transparency=False)
        # load the shields
        self.blockers = []
        self.blockers.append(loadObject("blocker.png", pos=LPoint3(3.5, 0, -9.2), scale=3.7))
        self.blockers.append(loadObject("blocker.png", pos=LPoint3(-3.5, 0, -9.2), scale=3.7))
        self.blockers.append(loadObject("blocker.png", pos=LPoint3(11, 0, -9.2), scale=3.7))
        self.blockers.append(loadObject("blocker.png", pos=LPoint3(-11, 0, -9.2), scale=3.7))
        # create ship
        self.ship = Ship()
        # create the list of alien shots
        self.alien_shots = []
        # start listening to the keys
        self.accept("escape", sys.exit)
        self.accept("arrow_left",     self.setKey,  ["moveLeft", 1])
        self.accept("arrow_left-up",  self.setKey,  ["moveLeft", 0])
        self.accept("arrow_right",    self.setKey, ["moveRight", 1])
        self.accept("arrow_right-up", self.setKey, ["moveRight", 0])
        # list to
        self.accept("updateAlienShotPositions", self.updateAlienShotPositions)

        # load the repeated textures we need
        global open10pt
        open10pt = loadTexture("10pts_Open.png")
        global closed10pt 
        closed10pt = loadTexture("10pts_Closed.png")
        global open20pt 
        open20pt = loadTexture("20pts_Open.png")
        global closed20pt 
        closed20pt = loadTexture("20pts_Closed.png")
        global open30pt
        open30pt = loadTexture("30pts_Open.png")
        global closed30pt
        closed30pt = loadTexture("30pts_Closed.png")
        global alienBlast 
        alienBlast = loadTexture("alien_Blast.png")
        global arrow1
        arrow1 = loadTexture("arrow.png")
        global arrow2
        arrow2 = loadTexture("arrow_Second.png")
        global boltLeft
        boltLeft = loadTexture("bolt_Left.png")
        global boltRight
        boltRight = loadTexture("bolt_Right.png")
        global bulletImg
        bulletImg = loadTexture("bullet.png")

        self.spawnAliens()
        self.startTasks()
    def raycast(self):
        pFrom = LPoint3(-4, 0, 0.5)
        pTo = LPoint3(4, 0, 0.5)
        #pTo = pFrom + LVector3(1, 0, 0) * 99999

        # Raycast for closest hit
        result = self.world.ray_test_closest(pFrom, pTo)
        print(result.has_hit(), \
        result.get_hit_fraction(), \
        result.get_node(), \
        result.get_hit_pos(), \
        result.get_hit_normal())
示例#13
0
def UVPatchAABB(radius, x0, y0, x1, y1, offset):
    a = UVPatchPoint(radius, 0, 0, x0, y0, x1, y1, offset)
    b = UVPatchPoint(radius, 1, 0, x0, y0, x1, y1, offset)
    c = UVPatchPoint(radius, 1, 1, x0, y0, x1, y1, offset)
    d = UVPatchPoint(radius, 0, 1, x0, y0, x1, y1, offset)
    m = UVPatchPoint(radius, 0.5, 0.5, x0, y0, x1, y1, offset)
    x_min = min(a[0], b[0], c[0], d[0], m[0])
    y_min = min(a[1], b[1], c[1], d[1], m[1])
    z_min = min(a[2], b[2], c[2], d[2], m[2])
    x_max = max(a[0], b[0], c[0], d[0], m[0])
    y_max = max(a[1], b[1], c[1], d[1], m[1])
    z_max = max(a[2], b[2], c[2], d[2], m[2])
    return BoundingBox(LPoint3(x_min, y_min, z_min),
                       LPoint3(x_max, y_max, z_max))
示例#14
0
def test_nodepath_transform_composition():
    """Tests that NodePath composes transform states according to the path it holds."""
    from panda3d.core import PandaNode, NodePath, LPoint3, LVector3

    # Create 3 PandaNodes, and give each some interesting transform state:
    node1 = PandaNode('node1')
    node2 = PandaNode('node2')
    node3 = PandaNode('node3')

    node1.set_transform(node1.get_transform().set_pos(LPoint3(
        0, 0, 1)).set_hpr(LVector3(90, 0, -90)))
    node2.set_transform(node2.get_transform().set_pos(LPoint3(
        0, 1, 0)).set_hpr(LVector3(180, 180, 0)))
    node3.set_transform(node3.get_transform().set_pos(LPoint3(
        1, 0, 0)).set_hpr(LVector3(270, 0, 270)))

    # node3 is going to be attached under both node1 and node2 and we will
    # hold a path both ways:
    node1.add_child(node3)
    node2.add_child(node3)

    assert len(node1.children) == 1
    assert len(node2.children) == 1
    assert len(node3.children) == 0
    assert len(node1.parents) == 0
    assert len(node2.parents) == 0
    assert len(node3.parents) == 2

    # np1 is the path to node3 via node1:
    np1 = NodePath(node1).children[0]
    # np2 is the path to node3 via node2:
    np2 = NodePath(node2).children[0]

    # Both should point to node3:
    assert np1.node() == node3
    assert np2.node() == node3

    # However if we ask for the net transform to node3, it should compose:
    assert np1.get_transform(NodePath()) == node1.get_transform().compose(
        node3.get_transform())
    assert np2.get_transform(NodePath()) == node2.get_transform().compose(
        node3.get_transform())

    # If we ask for np1 RELATIVE to np2, it should compose like so:
    leg1 = node2.get_transform().compose(node3.get_transform())
    leg2 = node1.get_transform().compose(node3.get_transform())
    relative_transform = leg1.get_inverse().compose(leg2)
    assert np1.get_transform(np2) == relative_transform
示例#15
0
    def __init__( self, node, mouseWatcherNode ):

        self.node = node
        self.focusNode = render.attachNewNode("CameraFocusNode")
        self.attachmentNode = None
        self.attached = True

        self.focusPoint = LPoint3()

        self.mouseWatcherNode = mouseWatcherNode

        self.bForward = KeyboardButton.ascii_key('w')
        self.bBackward = KeyboardButton.ascii_key('s')
        self.bLeft = KeyboardButton.ascii_key('a')
        self.bRight = KeyboardButton.ascii_key('d')
        self.bSpeed = KeyboardButton.lshift()

        self.speed = 0.2

        self.zoom = 10

        self.ang = 0
        self.angY = math.pi*0.5

        self.lastMousePos = (0,0)
示例#16
0
 def create_points(self, radius=1.0):
     if IrregularGalaxyShape.noise is None:
         IrregularGalaxyShape.noise = StackedPerlinNoise3(1, 1, 1, 8, 4, 0.7)
     points = []
     colors = []
     sizes = []
     nb_points = self.nb_points
     sprite_size = self.sprite_size
     colors_list = [self.color1, self.color2]
     spread = self.spread
     zspread = self.zspread
     sersic_inv = 1. / self.sersic
     count = 0
     while count < nb_points:
         p = LPoint3(gauss(0.0, spread), gauss(0.0, spread), gauss(0.0, zspread))
         value = self.noise(p) * 0.5 + 0.5
         if value < 0.5:
             points.append(p * radius)
             color = choice(colors_list)
             color = color * (1 - 0.9 * pow(p.length(), sersic_inv))
             color[3] = 1.0
             colors.append(color)
             size = sprite_size + gauss(0, sprite_size)
             sizes.append(size)
             count += 1
     return (points, colors, sizes)
示例#17
0
def loadObject(tex=None,
               pos=LPoint3(0, 0),
               depth=SPRITE_POS,
               scale=1,
               transparency=True):
    # Todos los objetos usan el modelo de avión y se acoplan a la cámara
    # para que quede frente a la pantalla.
    obj = loader.loadModel("models/plane")
    obj.reparentTo(camera)

    # Establecer la posición inicial y la escala.
    obj.setPos(pos.getX(), depth, pos.getY())
    obj.setScale(scale)

    # Esto le dice a Panda que no se preocupe por el orden en que se dibujan las cosas
    # (es decir, deshabilite la prueba Z). Esto evita un efecto conocido como Z-fighting.
    obj.setBin("unsorted", 0)
    obj.setDepthTest(False)

    if transparency:
        # Habilita la mezcla de transparencias.
        obj.setTransparency(TransparencyAttrib.MAlpha)

    if tex:
        # Cargue y establezca la textura solicitada.
        tex = loader.loadTexture("textures/" + tex)
        obj.setTexture(tex, 1)

    return obj
示例#18
0
def loadObject(tex=None,
               pos=LPoint3(0, 0),
               depth=SPRITE_POS,
               scale=1,
               transparency=True):
    # Every object uses the plane model and is parented to the camera
    # so that it faces the screen.
    obj = loader.loadModel("models/plane")
    obj.reparentTo(camera)

    # Set the initial position and scale.
    obj.setPos(pos.getX(), depth, pos.getY())
    obj.setScale(scale)

    # This tells Panda not to worry about the order that things are drawn in
    # (ie. disable Z-testing).  This prevents an effect known as Z-fighting.
    obj.setBin("unsorted", 0)
    obj.setDepthTest(False)

    if transparency:
        # Enable transparency blending.
        obj.setTransparency(TransparencyAttrib.MAlpha)

    if tex:
        # Load and set the requested texture.
        tex = loader.loadTexture("textures/" + tex)
        obj.setTexture(tex, 1)

    return obj
示例#19
0
def break_asteroid(self, entity_id):
    number = randint(2, 3)
    i = 0
    while i < number:
        asteroid = loadObject("asteroid%d.png" % (randint(1, 3)),
                              scale=defines.AST_INIT_SCALE / number,
                              pos=LPoint3(23, 23))
        physic_debug, physic_body = new_physic_object(
            shape='circle',
            scale=defines.AST_INIT_SCALE / number,
            pos=defines.ENTITIES[entity_id]['BODY'].position)

        physic_body.linearVelocity.Set(
            defines.ENTITIES[entity_id]['BODY'].linearVelocity.x,
            defines.ENTITIES[entity_id]['BODY'].linearVelocity.y)
        physic_body.angularVelocity = defines.ENTITIES[entity_id][
            'BODY'].angularVelocity

        f = physic_body.GetWorldVector(localVector=(randint(-5, 5),
                                                    randint(-5, 5)))
        p = physic_body.GetWorldPoint(localPoint=(0.0, 0))
        physic_body.ApplyLinearImpulse(f, p, True)

        defines.ENTITIES[defines.ENTITY_ID] = {
            'CATEGORY': "asteroid",
            'NODE': asteroid,
            'PHYSIC_NODE': physic_debug,
            'BODY': physic_body,
            'SHIELD': 20,
            'ENERGY': 0
        }
        defines.ENTITY_ID += 1

        i += 1
示例#20
0
def init_planet_logo(self, pos=LPoint3(0, 0)):
    planet = loadObject("planet0.png", scale=2, pos=LPoint3(0, 0))
    task = taskMgr.doMethodLater(0.5,
                                 animate_planet,
                                 'animate planet',
                                 extraArgs=[planet, 0, defines.ENTITY_ID],
                                 appendTask=True)
    planet.reparentTo(render)
    planet.setPos(pos[0], 55, pos[1])
    defines.ENTITIES[defines.ENTITY_ID] = {
        'CATEGORY': 'menu_planet',
        'NODE': planet,
        'BUTTON': None,
        'TASK': task
    }
    defines.ENTITY_ID += 1
示例#21
0
    def getMouseCollisionToPlane(showBase, plane):
        mouseWatcherNode = showBase.mouseWatcherNode
        if mouseWatcherNode.hasMouse():
            mpos = mouseWatcherNode.getMouse()

            pos3d = LPoint3()
            nearPoint = LPoint3()
            farPoint = LPoint3()
            showBase.camLens.extrude(mpos, nearPoint, farPoint)

            render = showBase.render
            camera = showBase.camera
            if plane.intersectsLine(pos3d,
                                    render.getRelativePoint(camera, nearPoint),
                                    render.getRelativePoint(camera, farPoint)):
                return pos3d
        return None
示例#22
0
def square_position(x, y, z, board_size):
    # Gives the 3d position of a square based on x, y, z
    xx, yy, zz = board_size
    x = (x - (3.5 / 8) * xx) * SCALE
    y = (y - (3.5 / 8) * yy) * SCALE
    z = z * BOARD_HEIGHT * SCALE

    return LPoint3(x, y, z)
示例#23
0
 def __init__(self):
     self.obj = loadObject(scale=2.5, pos=LPoint3(0, 0, -12.5))
     self.shipTex = loadTexture("ship.png")
     self.explode1 = loadTexture("ship_explode_one.png")
     self.explode2 = loadTexture("ship_explode_two.png")
     self.obj.setTexture(self.shipTex, 1)
     self.speed = 6
     self.bullets = []
     self.lives = 3
     self.accept("space", self.fire)
示例#24
0
    def __init__(self, position=LPoint3(0,0), value=0, open_image=None, close_image=None, scale=1.5):

        self.pts = value
        self.open_tex = open_image
        self.close_tex = close_image
        self.obj = loadObject(pos=position, scale=scale)
        self.obj.setTexture(self.open_tex, 1)
        self.open = True

        self.accept('move', self.move)
        self.accept('moveDown', self.moveDown)
示例#25
0
	def __init__(self, name):
		self.name = name
		self.cell_x = 0
		self.cell_y = 0
		self.vel = LPoint3(0, 0, 0)

		self.c_node = base.render.attachNewNode(
			self.name+"_camera_node")


		self.panda_actor = Actor("models/panda-model", {"walk": "models/panda-walk4"})
		self.panda_actor.setScale(0.05, 0.05, 0.05)

		self.p_node = NodePath(self.name+"_phys_node")
		self.p_node.reparentTo(render)

		self.an = ActorNode("panda-phys")
		self.anp = self.p_node.attachNewNode(self.an)
		base.enableParticles()
		base.physicsMgr.attachPhysicalNode(self.an)
		self.panda_actor.reparentTo(self.anp)

		gravityFN=ForceNode('world-forces')
		gravityFNP=render.attachNewNode(gravityFN)
		#gravityForce=LinearVectorForce(0,0,-9.81) #gravity acceleration
		self.gravityForce=LinearVectorForce(0,0,-9.81)
		gravityFN.addForce(self.gravityForce)

		base.physicsMgr.addLinearForce(self.gravityForce)


		self.c_node.reparentTo(self.panda_actor)
		self.c_node.setCompass()
		#self.panda_actor.reparentTo(base.render)
		base.camera.reparentTo(self.c_node)

		self.box = loader.loadModel("box.egg")
		self.box.setScale(100, 100, 100)
		self.box.setPos(-180, 0, 0)
		self.boxc = self.box.find("**/Cube")
		self.boxc.node().setIntoCollideMask(BitMask32.bit(0))
		self.boxc.node().setFromCollideMask(BitMask32.allOff())

		self.ban = ActorNode("box-phys")
		base.physicsMgr.attachPhysicalNode(self.ban)

		self.bp_node = NodePath(self.name+"_phys_node2")
		self.bp_node.reparentTo(render)

		self.banp = self.bp_node.attachNewNode(self.ban)
		self.box.reparentTo(self.banp)

		self.boxc.show()
示例#26
0
    def __init__(self, parent, data_model: Location, position: np.ndarray,
                 hex_model):
        PandaNode.__init__(
            self,
            "location.%s.%s.%s" % (position[0], position[1], position[2]))

        self.parent = parent
        self.path = parent.attachNewNode(self)
        self.position = position
        self.data_model = data_model
        self.hex_model = hex_model

        # Compute the offset cubic coordinate to offset coordinates.
        x, y = cube_to_offset(self.position)
        if y % 2 == 0:
            self.rw_position = LPoint3(self.delta_x_center * x,
                                       self.delta_y_center * -y, 0)
        else:
            # Offset of x += sqrt(3)*(r) / 2
            self.rw_position = LPoint3(self.delta_x_center * (x + .5),
                                       self.delta_y_center * -y, 0)
示例#27
0
    def on_frame(self, controller):
        ### Get the most recent frame and report some basic information

        # print '手的方向向量的x坐标',hand.direction.x                           ## 获取手的方向向量 【x,y,z】
        # print '手的法向量的x坐标',        hand.palm_normal.x                  ##获取当前手的法向量 【x,y,z】
        # print '手的握紧程度',               hand.grab_strength                      ## 获取手的抓取强度,在0-1之间,当手完全张开时强度为0,当手握成拳头时为1
        # print '手的位置的x坐标',     hand.stabilized_palm_position.x                 ## 获取手的当前坐标位置 【x,y,z】
        # print "手的ID是:",               hand.id                                     ## 获取手的ID,在连贯捕捉的帧中这个ID是相同的,但是中间断开时会改变
        # print '这是左手吗? ',          hand.is_left                                    ## 判断当前手是否为左手
        # print '这是右手吗?  ',             hand.is_right                               ## 判断当前手是否为右手
        # print '当前手对象有效吗? ',   hand.is_valid                               ## 判断当前手对象是否有效
        # print '手的移动速度的x坐标',   hand.palm_velocity.x                    ## 获取当前手的移动速度 ms/s 【x,y,z】
        # print '手的稳定位置的x坐标', hand.stabilized_palm_position.x   ## 获取当前手掌的稳定位置,这个位置的变化会更平滑稳定,利于2D交互
        # print '当前手被捕获的时间',    hand.time_visible                           ## 当前手已经被leapmotion捕获的时间
        if not self.enable:
            return
        frame = controller.frame()
        for hand in frame.hands:
            if not hand.is_valid:
                continue
            if hand.is_left:
                # if hand.time_visible - self.preTime < 0.005:
                #     print hand.time_visible,' ',self.preTime
                #     return
                # self.preTime = hand.time_visible

                newPos = [0, 0, 0]
                iBox = frame.interaction_box
                leapPoint = hand.palm_position
                pos = iBox.normalize_point(leapPoint, False)
                pos = LPoint3(pos[0], pos[1], pos[2])
                pos[0] = pos[0] if pos[0] > 0 else 0
                pos[0] = pos[0] if pos[0] < 1 else 1
                pos[1] = pos[1] if pos[1] > 0 else 0
                pos[1] = pos[1] if pos[1] < 1 else 1

                for i in range(0, 2):
                    if abs(self.LastHand[i] - pos[i]
                           ) < 0.001:  # or abs(self.LastHand[i]-pos[i]) > 0.2:
                        pos[i] = self.LastHand[i]
                    else:
                        self.LastHand[i] = pos[i]
                base.messenger.send('new-pos', [pos])
            if hand.is_right:
                #print "hand.sphere_radius",hand.sphere_radius
                if hand.sphere_radius < 45:
                    base.messenger.send('fire')
                    #print 'fire'

                #print hand.palm_normal
                if hand.palm_normal[1] > 0.45:
                    base.messenger.send('pick')
 def query_elevation(self, xy_pos=None):
     """
     Query elevation for xy_pos if present, else for vehicle position.
     No xy_pos means verbose mode.
     """
     query_pos = xy_pos or self.vehicleNP.get_pos()
     """
     This method is accurate and may be useful for placing 
     objects on the terrain surface.
     """
     result = self.world.ray_test_closest(
         LPoint3(query_pos.x, query_pos.y, -10000),
         LPoint3(query_pos.x, query_pos.y, 10000))
     if result.has_hit():
         hit_pos = result.get_hit_pos()
         if not xy_pos:
             print("Bullet heightfield elevation at "
                 "X {:.2f} | Y {:.2f} is {:.3f}".format(
                 hit_pos.x, hit_pos.y, hit_pos.z))
     else:
         hit_pos = None
         if not xy_pos:
             print("Could not query elevation at {}".format(xy_pos))
     
     """
     This method is less accurate than the one above.
     Under heavy ray-testing stress (ray tests are performed for all vehicle
     wheels, the above elevation query etc.) Bullet sometimes seems to be a
     little unreliable.
     """
     texspace_pos = self.terrain.get_relative_point(render, query_pos)
     stm_pos = self.terrain_node.uv_to_world(
         LTexCoord(texspace_pos.x, texspace_pos.y))
     if not xy_pos:
         print("ShaderTerrainMesh elevation at "
             "X {:.2f} | Y {:.2f} is {:.3f}".format(
             stm_pos.x, stm_pos.y, stm_pos.z))
     
     return hit_pos or stm_pos
示例#29
0
    def do_shoot(self):
        # Get from/to points from mouse click
        pMouse = base.mouseWatcherNode.get_mouse()
        pFrom = LPoint3()
        pTo = LPoint3()
        base.camLens.extrude(pMouse, pFrom, pTo)

        pFrom = render.get_relative_point(base.cam, pFrom)
        pTo = render.get_relative_point(base.cam, pTo)

        # Calculate initial velocity
        v = pTo - pFrom
        v.normalize()
        v *= 100.0

        # Create bullet
        shape = BulletSphereShape(0.3)
        body = BulletRigidBodyNode('Bullet')
        bodyNP = self.worldNP.attach_new_node(body)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_linear_velocity(v)
        bodyNP.node().set_ccd_motion_threshold(1e-7)
        bodyNP.node().set_ccd_swept_sphere_radius(0.50)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(pFrom)

        visNP = loader.load_model('models/ball.egg')
        visNP.set_scale(0.8)
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyNP.node())

        # Remove the bullet again after 2 seconds
        taskMgr.do_method_later(2,
                                self.do_remove,
                                'doRemove',
                                extraArgs=[bodyNP],
                                appendTask=True)
示例#30
0
 def _create(self):
     for monster in self.monsters:
         print 'remove'
         monster.detachSound()
         monster.model.cleanup()
         monster.model.removeNode()
     self.monsters=[]
     for i in range(0,1):
         print i
         monster = MonsterFactory.create('Minotaur',LPoint3(0,i*50,0),render)
         if isinstance(monster,Monster):
             self.monsters.append(monster)
             # 火焰
             monster.fire2()
示例#31
0
    def do_shoot(self, ccd):
        # Get from/to points from mouse click
        pMouse = base.mouseWatcherNode.get_mouse()
        pFrom = LPoint3()
        pTo = LPoint3()
        base.camLens.extrude(pMouse, pFrom, pTo)

        pFrom = render.get_relative_point(base.cam, pFrom)
        pTo = render.get_relative_point(base.cam, pTo)

        # Calculate initial velocity
        v = pTo - pFrom
        v.normalize()
        v *= 10000.0

        # Create bullet
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))
        body = BulletRigidBodyNode('Bullet')
        bodyNP = self.worldNP.attach_new_node(body)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(2.0)
        bodyNP.node().set_linear_velocity(v)
        bodyNP.set_pos(pFrom)
        bodyNP.set_collide_mask(BitMask32.all_on())

        if ccd:
            bodyNP.node().set_ccd_motion_threshold(1e-7)
            bodyNP.node().set_ccd_swept_sphere_radius(0.50)

        self.world.attach(bodyNP.node())

        # Remove the bullet again after 1 second
        taskMgr.do_method_later(1,
                                self.do_remove,
                                'doRemove',
                                extraArgs=[bodyNP],
                                appendTask=True)