def setupCollision(self): cs = CollisionSphere(0, 0, 0, 10) cnodePath = self.player.attachNewNode(CollisionNode('cnode')) cnodePath.node().addSolid(cs) cnodePath.show() for o in self.OBS: ct = CollisionBox(0, 1, 1, 0.5) cn = o.attachNewNode(CollisionNode('ocnode')) cn.node().addSolid(ct) cn.show() pusher = CollisionHandlerPusher() pusher.addCollider(cnodePath, self.player) self.cTrav = CollisionTraverser() self.cTrav.addCollider(cnodePath, pusher) self.cTrav.showCollisions(render)
def gen_box_cdnp(pdnp, name='cdnp_box', radius=0.01): """ :param obstacle: :return: author: weiwei date: 20180811 """ bottom_left, top_right = pdnp.getTightBounds() center = (bottom_left + top_right) / 2.0 # enlarge the bounding box bottom_left -= (bottom_left - center).normalize() * radius top_right += (top_right - center).normalize() * radius collision_primitive = CollisionBox(bottom_left, top_right) collision_node = CollisionNode(name) collision_node.addSolid(collision_primitive) return collision_node
def CreateGfx( self, loader, idx ): # idx is neccesary to be able to track it down for mouse picking self.__node = loader.loadModel("models/cube") self.__node.setPos(0, 0, 0) self.__node.setScale(0.5, 0.5, 0.5) self.__node.setTag("clickable", str(idx)) # to be able to click on it self.__node.setName("cell") # COLLISION collBox = CollisionBox(self.__node.getPos(), 1.0, 1.0, 1.0) cnodePath = self.__node.attachNewNode(CollisionNode("cnode")) cnodePath.node().addSolid(collBox) self.UpdateState(False, False)
def CreateGfx(self, loader, idx): self.__node = loader.loadModel("models/cube") #self.__node.setRenderModeFilledWireframe(LColor(0, 0, 0, 1.0)) self.__node.setPos(0, 0, 0) self.__node.setScale(0.5, 0.5, 0.5) self.__node.setTag("clickable", str(idx)) # to be able to click on it self.__node.setName("inputBit") # COLLISION collBox = CollisionBox(self.__node.getPos(), 1.0, 1.0, 1.0) cnodePath = self.__node.attachNewNode(CollisionNode("cnode")) cnodePath.node().addSolid(collBox) self.UpdateState()
def __init__(self, parent, name): self.chars = [] self.enemies = [] self.parent = parent self.name = name self.angle = 0 self.cells = 2 # rest zone collisions # used to detect pointing the Rest Zone by mouse col_node = CollisionNode(name) col_node.setFromCollideMask(NO_MASK) col_node.setIntoCollideMask(MOUSE_MASK) col_node.addSolid( CollisionBox(Point3(-0.09, -0.36, 0.15), Point3(0.09, -0.17, 0.27)) ) parent.attachNewNode(col_node)
def create_collision(self): """Creates self.coll_node from self.terrain_map.""" map_size = len(self.terrain_map) start_pos = -map_size * map_params.unit_size / 2 box_size = Vec3(map_params.unit_size, map_params.unit_size, map_params.height) for i in range(map_size): for j in range(map_size): current_position = Point3(start_pos + i * map_params.unit_size, start_pos + j * map_params.unit_size, 0) if isinstance(self.get_tile(i, j), Wall): self.coll_node.addSolid( CollisionBox(current_position, current_position + box_size))
def notify(self, event: Event) -> None: if isinstance(event, MapUpdateEvent): z_offset = 1 if self.__map.dim == 3 else self.__map.depth for p in event.updated_cells: if p.n_dim == 2: p = Point(*p, 0) if bool(self.__data[p.values] & MapData.TRAVERSABLE_MASK): self.__points.append(p) idx = self.__cn.add_solid(CollisionBox(p.values, Point3(p.x+1, p.y+1, p.z-z_offset))) assert idx == (len(self.__points) - 1) else: try: i = self.__points.index(p) except ValueError: continue self.__cn.remove_solid(i) self.__points.pop(i)
def __gencdboxcn(self, pandanp, name='boxcd', radius=15.0): """ :param obstacle: :return: author: weiwei date: 20180811 """ cnp = CollisionNode(name) bottomLeft, topRight = pandanp.getTightBounds() center = (bottomLeft + topRight) / 2.0 # enlarge the bounding box bottomLeft -= (bottomLeft - center).normalize() * radius topRight += (topRight - center).normalize() * radius cbn = CollisionBox(bottomLeft, topRight) cnp.addSolid(cbn) return cnp
def createSquareCollider(self, px, pz, w, h, modelName, collisionNodeName, nodeName, enableFunction, disableFunction, texture, mask): obj = self.scene.attachNewNode(nodeName) hitbox = CollisionBox(Point3(0, 0, 0), w, 5, h) cNodePath = obj.attachNewNode(CollisionNode(collisionNodeName)) cNodePath.node().addSolid(hitbox) cNodePath.node().setIntoCollideMask(mask) cNodePath.node().setFromCollideMask(mask) #cNodePath.show() base.cTrav.addCollider(cNodePath, self.collisionHandlerEvent) self.scene.find(f'root/{modelName}').reparentTo(obj) obj.setPos(px, 0, pz) obj.setTexture(texture) self.accept(f'into-{collisionNodeName}', enableFunction) self.accept(f'outof-{collisionNodeName}', disableFunction) return obj
def __init__(self, base, n, x, y, z): self.base = base self.n = n self.health = 4 self.np = base.loader.loadModel("./mdl/enemy.egg") self.np.setColor(1, 1, 0, 1) self.np.reparentTo(base.render) self.np.setPos(x, y, z) self.np.setAlphaScale(0.) base.target = self self.radar = OnscreenImage(image="./png/radar.png", pos=Vec3(0), scale=0.01) self.radar.setTransparency(TransparencyAttrib.MAlpha) # collisions cn = CollisionNode("enemy" + str(n)) cn.addSolid(CollisionBox(0, 2.5, 2, 0.5)) cn.setCollideMask(BitMask32(0x1) | BitMask32(0x2)) # cc = self.np.attachNewNode(cn) self.np.attachNewNode(cn) base.accept("fighter-into-enemy" + str(n), self.ship_collision) base.accept("bullet-into-enemy" + str(n), self.bullet_collision) base.accept("missile-into-enemy" + str(n), self.missile_collision) # sound self.snd_crash = base.loader.loadSfx("./snd/crash.flac") self.snd_blip = base.audio3d.loadSfx("./snd/blip.flac") self.snd_hit = base.loader.loadSfx("./snd/hit.flac") self.snd_explode = base.loader.loadSfx("./snd/explosion.flac") base.audio3d.attachSoundToObject(self.snd_blip, self.np) base.audio3d.setSoundVelocityAuto(self.snd_blip) base.audio3d.attachSoundToObject(self.snd_crash, self.np) base.audio3d.setSoundVelocityAuto(self.snd_crash) base.audio3d.attachSoundToObject(self.snd_hit, self.np) base.audio3d.setSoundVelocityAuto(self.snd_hit) base.audio3d.attachSoundToObject(self.snd_explode, self.np) base.audio3d.setSoundVelocityAuto(self.snd_explode) self.snd_blip.setLoop(True) self.snd_blip.play() self.setAI()
def setupBoxCollider(self, node, px, py, pz, w, d, h, nm, colliderEventHandler, fromCollisionMask=0, intoCollisionMask=0): hitBox = CollisionBox(Point3(px, py, pz), w, d, h) cnodePath = node.attachNewNode(CollisionNode(nm)) cnodePath.node().addSolid(hitBox) cnodePath.node().setIntoCollideMask(intoCollisionMask) cnodePath.node().setFromCollideMask(fromCollisionMask) cnodePath.show() base.cTrav.addCollider(cnodePath, colliderEventHandler)
def initKeyDoors(self): i = 0 for keyDoor in self.KeyDoorLogic: for door, value in self.doorControls.iteritems(): if keyDoor == door.getParent().getName(): c = Point3(0,0,0) p1 = Point3(c.getX()-1, c.getY()-0.8, c.getZ()) p2 = Point3(c.getX()+1, c.getY()+0.8, c.getZ()+2) keyDoorBox = CollisionBox(p1, p2) keyDoorBox.setTangible(False) keyDoorColNP = door.getParent().attachNewNode(CollisionNode('keyDoorActivation%d'%i)) keyDoorColNP.node().addSolid(keyDoorBox) keyDoorName = door.getParent().getName() self.accept("playerCollision-in-keyDoorActivation%d"%i, self.__setActivateElement, extraArgs=[True, keyDoorName, "door"]) self.accept("playerCollision-out-keyDoorActivation%d"%i, self.__setActivateElement, extraArgs=[False, keyDoorName, "door"]) i+=1
def __init__(self, model, id_, y_positions, enemy_handler, class_data): EnemyUnit.__init__( self, id_, "Gun Dodge", class_data, model, y_positions, enemy_handler, ) self._col_node = self._init_col_node( SHOT_RANGE_MASK, MOUSE_MASK, CollisionBox(Point3(-0.04, -0.12, -0.02), Point3(0.04, 0.11, 0.06)), ) base.common_ctrl.traverser.addCollider( # noqa: F821 self._col_node, enemy_handler) self._shoot_seq = self._set_shoot_anim() self._explosion = base.effects_mgr.explosion_big(self) # noqa: F821 self._smoke = base.effects_mgr.burn_smoke(self) # noqa: F821
def __init__(self, parent, name, positions, angle, arrow_pos): self.parent = parent self.name = name self.chars = [] self.is_covered = False # enemies within shooting range of this part self.enemies = [] self.angle = angle self._cells = positions self._arrow = self._prepare_arrow(name, arrow_pos) # shooting range for this TrainPart col_node = CollisionNode("shoot_zone_" + name) col_node.setFromCollideMask(NO_MASK) col_node.setIntoCollideMask(SHOT_RANGE_MASK) col_node.addSolid(CollisionBox(Point3(-0.4, -0.06, 0), Point3(0.4, 1, 0.08))) col_np = self.parent.attachNewNode(col_node) col_np.setPos(arrow_pos[0], arrow_pos[1], 0) col_np.setH(angle) base.accept("into-shoot_zone_" + name, self.enemy_came) # noqa: F821 base.accept("out-shoot_zone_" + name, self.enemy_leave) # noqa: F821
def gen_cylindrical_cdnp(pdnp, name='cdnp_cylinder', radius=0.01): """ :param trimeshmodel: :param name: :param radius: :return: author: weiwei date: 20200108 """ bottom_left, top_right = pdnp.getTightBounds() center = (bottom_left + top_right) / 2.0 # enlarge the bounding box bottomleft_adjustvec = bottom_left - center bottomleft_adjustvec[2] = 0 bottomleft_adjustvec.normalize() bottom_left += bottomleft_adjustvec * radius topright_adjustvec = top_right - center topright_adjustvec[2] = 0 topright_adjustvec.normalize() top_right += topright_adjustvec * radius bottomleft_pos = da.pdv3_to_npv3(bottom_left) topright_pos = da.pdv3_to_npv3(top_right) collision_node = CollisionNode(name) for angle in np.nditer(np.linspace(math.pi / 10, math.pi * 4 / 10, 4)): ca = math.cos(angle) sa = math.sin(angle) new_bottomleft_pos = np.array([ bottomleft_pos[0] * ca, bottomleft_pos[1] * sa, bottomleft_pos[2] ]) new_topright_pos = np.array( [topright_pos[0] * ca, topright_pos[1] * sa, topright_pos[2]]) new_bottomleft = da.npv3_to_pdv3(new_bottomleft_pos) new_topright = da.npv3_to_pdv3(new_topright_pos) collision_primitive = CollisionBox(new_bottomleft, new_topright) collision_node.addSolid(collision_primitive) return collision_node
def CreateBasement( self ): # it will create basement object, just for case that nothing is drawn to be not lost # Load the environment model. self.cube = self.base.loader.loadModel(os.path.join(os.getcwd(),"models/worldOrigin")) # /media/Data/Data/Panda3d/ # Reparent the model to render. self.cube.reparentTo(self.render) # Apply scale and position transforms on the model. self.cube.setScale(3, 3, 3) self.cube.setPos(-8, -40, 0) self.cube.setColor(1.0, 0, 0, 1.0) #self.cube.setRenderModeThickness(5) #self.cube.setRenderModeFilledWireframe(LColor(0, 0, 0, 1.0)) # COLLISION collBox = CollisionBox(self.cube.getPos(), 10.0, 10.0, 10.0) cnodePath = self.cube.attachNewNode(CollisionNode("cnode")) cnodePath.node().addSolid(collBox) self.cube.setTag("clickable", "1")
def _base_combined_cdnp(name, radius): collision_node = CollisionNode(name) collision_primitive_c0 = CollisionBox(Point3(0.54, 0.0, 0.39), x=.54 + radius, y=.6 + radius, z=.39 + radius) collision_node.addSolid(collision_primitive_c0) collision_primitive_c1 = CollisionBox(Point3(0.06, 0.0, 0.9), x=.06 + radius, y=.375 + radius, z=.9 + radius) collision_node.addSolid(collision_primitive_c1) collision_primitive_c2 = CollisionBox(Point3(0.18, 0.0, 1.77), x=.18 + radius, y=.21 + radius, z=.03 + radius) collision_node.addSolid(collision_primitive_c2) collision_primitive_l0 = CollisionBox(Point3(0.2425, 0.345, 1.33), x=.1225 + radius, y=.06 + radius, z=.06 + radius) collision_node.addSolid(collision_primitive_l0) collision_primitive_r0 = CollisionBox(Point3(0.2425, -0.345, 1.33), x=.1225 + radius, y=.06 + radius, z=.06 + radius) collision_node.addSolid(collision_primitive_r0) collision_primitive_l1 = CollisionBox(Point3(0.21, 0.405, 1.07), x=.03 + radius, y=.06 + radius, z=.29 + radius) collision_node.addSolid(collision_primitive_l1) collision_primitive_r1 = CollisionBox(Point3(0.21, -0.405, 1.07), x=.03 + radius, y=.06 + radius, z=.29 + radius) collision_node.addSolid(collision_primitive_r1) return collision_node
def _base_combined_cdnp(name, radius): collision_node = CollisionNode(name) collision_primitive_c0 = CollisionBox(Point3(0.18, 0.0, 0.105), x=.61 + radius, y=.41 + radius, z=.105 + radius) collision_node.addSolid(collision_primitive_c0) collision_primitive_c1 = CollisionBox(Point3(0.0, 0.0, 0.4445), x=.321 + radius, y=.321 + radius, z=.2345 + radius) collision_node.addSolid(collision_primitive_c1) collision_primitive_c2 = CollisionBox(Point3(0.0, 0.0, 0.8895), x=.05 + radius, y=.05 + radius, z=.6795 + radius) collision_node.addSolid(collision_primitive_c2) collision_primitive_c3 = CollisionBox(Point3(0.0, 0.0, 1.619), x=.1 + radius, y=.275 + radius, z=.05 + radius) collision_node.addSolid(collision_primitive_c3) collision_primitive_l0 = CollisionBox(Point3(0.0, 0.300, 1.669), x=.1 + radius, y=.029 + radius, z=.021 + radius) collision_node.addSolid(collision_primitive_l0) collision_primitive_r0 = CollisionBox(Point3(0.0, -0.300, 1.669), x=.1 + radius, y=.029 + radius, z=.021 + radius) collision_node.addSolid(collision_primitive_r0) return collision_node
def __init__(self): ShowBase.__init__(self) self.params = { "mouse_x": 0, "mouse_y": 0, } self.disableMouse() self.cmd_mgr = commandmgr.TheWorldCommandMgr(self) util.hidden_relative_mouse(self) for cmd_str, cmd_fn in self.cmd_mgr.mapping.items(): self.accept(cmd_str, cmd_fn) # environment self.setBackgroundColor(.0, .0, .0, 1) # # ground self.ground_cube = self.loader.loadModel("cuby.gltf") self.ground_cube.setColor(1, 1, 1, 1) ground_cube_size = Vec3(2, 2, .4) self.ground_cube.setScale(ground_cube_size) self.ground = self.render.attachNewNode("ground") grid_size = 5 grid_max = grid_size - 1 dist = 8 grid_coordinates = itertools.product(range(grid_size), range(grid_size)) def normalize(x_y): x, y = x_y return (x - grid_max / 2) * dist, (y - grid_max / 2) * dist for x, y in map(normalize, grid_coordinates): placeholder = self.ground.attachNewNode("placeholder") placeholder.setPos(x, y, -ground_cube_size.z) self.ground_cube.instanceTo(placeholder) # collision ground coll_node = CollisionNode(f"ground_{x}_{y}") coll_node.setFromCollideMask(CollideMask.allOff()) coll_node.setIntoCollideMask(CollideMask.bit(0)) nodepath = placeholder.attachNewNode(coll_node) nodepath.node().addSolid( CollisionBox(Point3(0, 0, 0), ground_cube_size.x, ground_cube_size.y, ground_cube_size.z)) # lighting ambient_light = AmbientLight("ambient_light") ambient_light.setColor((.2, .2, .2, 1)) alight = self.render.attachNewNode(ambient_light) self.render.setLight(alight) # actor self.actor_obj = Actor(self, self.render, "cuby.gltf") self.actor = self.actor_obj.node self.actor.setColor(cube_color) # # collision actor self.cTrav = CollisionTraverser('traverser') self.cTrav.showCollisions(self.actor) self.actor_coll = CollisionNode('actor') self.actor_coll.addSolid(CollisionBox(Point3(0, 0, 0), 1, 1, 1)) self.actor_coll.setFromCollideMask(CollideMask.bit(0)) self.actor_coll.setIntoCollideMask(CollideMask.allOff()) self.actor_coll_np = self.actor.attachNewNode(self.actor_coll) self.pusher = CollisionHandlerPusher() self.pusher.addCollider(self.actor_coll_np, self.actor) self.cTrav.addCollider(self.actor_coll_np, self.pusher) # lighting self.centerlight_np = self.render.attachNewNode("basiclightcenter") self.centerlight_np.hprInterval(4, (360, 0, 0)).loop() d, h = 8, 1 self.basic_point_light((-d, 0, h), (.0, .0, .7, 1), "left_light") self.basic_point_light((d, 0, h), (.0, .7, 0, 1), "right_light") self.basic_point_light((0, d, h), (.7, .0, .0, 1), "front_light") self.basic_point_light((0, -d, h), (1, 1, 1, 1), "back_light") self.actor_stater = Stater(self.actor) self.cmd_mgr.set_actor_stater(self.actor_stater) self.actor_mover = Mover(self, self.actor_obj, self.actor_stater) self.camera.wrtReparentTo(self.actor) self.camera.setPos(Vec3(0, 4, 1).normalized() * cam_dist) self.camera.lookAt(0, 0, 0) self.taskMgr.add(self.update_params, "paramsTask") self.taskMgr.add(self.actor_mover.execute, "moveTask") self.taskMgr.add(self.log, "logTask") self.render.setShaderAuto()
def generateNode(self): self.destroy() self.node = NodePath('gameobjectnode') self.node.setTwoSided(True) self.node.reparentTo(self.parent.node) if self.properties['avoidable'] == True: self.node.setTag("avoidable", 'true') else: self.node.setTag("avoidable", 'false') #setting scripting part self.node.setTag("onWalked", self.onWalked) self.node.setTag("onPicked", self.onPicked) #set unique id self.node.setTag("id", self.properties['id']) tex = loader.loadTexture(resourceManager.getResource(self.properties['url'])+'.png') tex.setWrapV(Texture.WM_clamp) tex.setWrapU(Texture.WM_clamp) #this is true pixel art #change to FTLinear for linear interpolation between pixel colors tex.setMagfilter(Texture.FTNearest) tex.setMinfilter(Texture.FTNearest) xorig = tex.getOrigFileXSize() / self.baseDimension yorig = tex.getOrigFileYSize() / self.baseDimension xscaled = (tex.getOrigFileXSize() / self.baseDimension) * self.properties['scale'] yscaled = (tex.getOrigFileYSize() / self.baseDimension) * self.properties['scale'] self.node.setTag("xscaled", str(xscaled)) self.node.setTag("yscaled", str(yscaled)) cm = CardMaker("tileobject") cm.setFrame(0,xorig,0,yorig) ts = TextureStage('ts') ts.setMode(TextureStage.MDecal) # distinguish between 3d collisions (for objects with an height and sensible self.properties['inclination']) # and 2d collisions for plain sprites if self.properties['walkable'] == 'false': if self.properties['collisionmode'] == "3d": #must handle differently objects which are small and big if xscaled < 1: self.collisionTube = CollisionBox(LPoint3f(0.5 - xscaled/2 - self.properties['offsetwidth'],0,0),LPoint3f(0.5 + xscaled/2 + self.properties['offsetwidth'],0.1,0.3 + self.properties['offsetheight'])) if xscaled >= 1: self.collisionTube = CollisionBox(LPoint3f(0 - self.properties['offsetwidth'],0,0),LPoint3f(xscaled + self.properties['offsetwidth'],0.1,0.3 + self.properties['offsetheight'])) self.collisionNode = CollisionNode('objectSphere') self.collisionNode.addSolid(self.collisionTube) self.collisionNodeNp = self.node.attachNewNode(self.collisionNode) self.collisionNodeNp.setX(self.properties['offsethorizontal']) self.collisionNodeNp.setZ(self.properties['offsetvertical']) self.collisionNodeNp.setX(self.collisionNodeNp.getX()+self.properties['offsetcollisionh']) self.collisionNodeNp.setZ(self.collisionNodeNp.getZ()+self.properties['offsetcollisionv']+0.1) if main.editormode: self.collisionNodeNp.show() elif self.properties['collisionmode'] == "2d": #must handle differently objects which are small and big if xscaled < 1: self.collisionTube = CollisionBox(LPoint3f(0.5 - xscaled/2,0,0),LPoint3f(0.5 + xscaled/2,yscaled,0.3)) if xscaled >= 1: self.collisionTube = CollisionBox(LPoint3f(0,0,0),LPoint3f(xscaled,yscaled,0.3)) self.collisionNode = CollisionNode('objectSphere') self.collisionNode.addSolid(self.collisionTube) self.collisionNodeNp = self.node.attachNewNode(self.collisionNode) self.collisionNodeNp.setP(-(270-int(self.properties['inclination']))) self.collisionNodeNp.setX(self.properties['offsethorizontal']) self.collisionNodeNp.setZ(self.properties['offsetvertical']) self.collisionNodeNp.setX(self.collisionNodeNp.getX()+self.properties['offsetcollisionh']) self.collisionNodeNp.setZ(self.collisionNodeNp.getZ()+self.properties['offsetcollisionv']+0.1) if main.editormode: self.collisionNodeNp.show() geomnode = NodePath(cm.generate()) if xscaled >= 1: geomnode.setX(0) if xscaled < 1: geomnode.setX(0.5 - xscaled/2) geomnode.setScale(self.properties['scale']) geomnode.setX(geomnode.getX()+self.properties['offsethorizontal']) geomnode.setZ(geomnode.getZ()+self.properties['offsetvertical']) geomnode.setY(-self.properties['elevation']) geomnode.setP(-(360-int(self.properties['inclination']))) geomnode.setTexture(tex) geomnode.setTransparency(TransparencyAttrib.MAlpha) geomnode.reparentTo(self.node)
def generateNode(self): self.destroy() self.node = NodePath('gameobjectnode') self.node.setTwoSided(True) self.node.reparentTo(self.parent.node) if self.properties['avoidable'] == True: self.node.setTag("avoidable", 'true') else: self.node.setTag("avoidable", 'false') #setting scripting part self.node.setTag("onWalked", self.onWalked) self.node.setTag("onPicked", self.onPicked) #set unique id self.node.setTag("id", self.properties['id']) tex = loader.loadTexture(resourceManager.getResource(self.properties['url'])+'.png') tex.setWrapV(Texture.WM_clamp) tex.setWrapU(Texture.WM_clamp) #this is true pixel art #change to FTLinear for linear interpolation between pixel colors tex.setMagfilter(Texture.FTNearest) tex.setMinfilter(Texture.FTNearest) xorig = tex.getOrigFileXSize() / self.baseDimension yorig = tex.getOrigFileYSize() / self.baseDimension xscaled = (tex.getOrigFileXSize() / self.baseDimension) * self.properties['scale'] yscaled = (tex.getOrigFileYSize() / self.baseDimension) * self.properties['scale'] self.node.setTag("xscaled", str(xscaled)) self.node.setTag("yscaled", str(yscaled)) cm = CardMaker("tileobject") cm.setFrame(0,xorig,0,yorig) ts = TextureStage('ts') ts.setMode(TextureStage.MDecal) # distinguish between 3d collisions (for objects with an height and sensible self.properties['inclination']) # and 2d collisions for plain sprites if self.properties['walkable'] == 'false': if self.properties['collisionmode'] == "3d": #must handle differently objects which are small and big if xscaled < 1: self.collisionTube = CollisionBox(LPoint3f(0.5 - xscaled/2 - self.properties['offsetwidth'],0,0),LPoint3f(0.5 + xscaled/2 + self.properties['offsetwidth'],0.1,0.3 + self.properties['offsetheight'])) if xscaled >= 1: self.collisionTube = CollisionBox(LPoint3f(0 - self.properties['offsetwidth'],0,0),LPoint3f(xscaled + self.properties['offsetwidth'],0.1,0.3 + self.properties['offsetheight'])) self.collisionNode = CollisionNode('objectSphere') self.collisionNode.addSolid(self.collisionTube) self.collisionNodeNp = self.node.attachNewNode(self.collisionNode) self.collisionNodeNp.setX(self.properties['offsethorizontal']) self.collisionNodeNp.setZ(self.properties['offsetvertical']) self.collisionNodeNp.setX(self.collisionNodeNp.getX()+self.properties['offsetcollisionh']) self.collisionNodeNp.setZ(self.collisionNodeNp.getZ()+self.properties['offsetcollisionv']+0.1) if main.editormode: self.collisionNodeNp.show() elif self.properties['collisionmode'] == "2d": #must handle differently objects which are small and big if xscaled < 1: self.collisionTube = CollisionBox(LPoint3f(0.5 - xscaled/2 - self.properties['offsetwidth'],0,0),LPoint3f(0.5 + xscaled/2 + self.properties['offsetwidth'],yscaled + self.properties['offsetheight'],0.3)) if xscaled >= 1: self.collisionTube = CollisionBox(LPoint3f(0 - self.properties['offsetwidth'],0,0),LPoint3f(xscaled + self.properties['offsetwidth'],yscaled + self.properties['offsetheight'],0.3)) self.collisionNode = CollisionNode('objectSphere') self.collisionNode.addSolid(self.collisionTube) self.collisionNodeNp = self.node.attachNewNode(self.collisionNode) self.collisionNodeNp.setP(-(270-int(self.properties['inclination']))) self.collisionNodeNp.setX(self.properties['offsethorizontal']) self.collisionNodeNp.setZ(self.properties['offsetvertical']) self.collisionNodeNp.setX(self.collisionNodeNp.getX()+self.properties['offsetcollisionh']) self.collisionNodeNp.setZ(self.collisionNodeNp.getZ()+self.properties['offsetcollisionv']+0.1) if main.editormode: self.collisionNodeNp.show() geomnode = NodePath(cm.generate()) if geomnode.node().isGeomNode(): vdata = geomnode.node().modifyGeom(0).modifyVertexData() writer = GeomVertexWriter(vdata, 'vertex') reader = GeomVertexReader(vdata, 'vertex') ''' this part apply rotation flattening to the perspective view by modifying directly structure vertices ''' i = 0 #counter while not reader.isAtEnd(): v = reader.getData3f() x = v[0] y = v[1] z = v[2] newx = x newy = y newz = z if self.properties['rotation'] == -90.0: if i == 0: newx = math.fabs(math.cos(math.radians(self.properties['inclination']))) * z newz = 0 ssen = math.fabs(math.sin(math.radians(self.properties['inclination']))) * z sparsen = math.fabs(math.sin(math.radians(self.properties['inclination']))) * ssen spercos = math.fabs(math.cos(math.radians(self.properties['inclination']))) * ssen newy -= spercos newz += sparsen if i == 2: newx += math.fabs(math.cos(math.radians(self.properties['inclination']))) * z newz = 0 ssen = math.fabs(math.sin(math.radians(self.properties['inclination']))) * z sparsen = math.fabs(math.sin(math.radians(self.properties['inclination']))) * ssen spercos = math.fabs(math.cos(math.radians(self.properties['inclination']))) * ssen newy -= spercos newz += sparsen writer.setData3f(newx, newy, newz) i += 1 #increase vertex counter if xscaled >= 1: geomnode.setX(0) if xscaled < 1: geomnode.setX(0.5 - xscaled/2) geomnode.setScale(self.properties['scale']) geomnode.setX(geomnode.getX()+self.properties['offsethorizontal']) geomnode.setZ(geomnode.getZ()+self.properties['offsetvertical']) geomnode.setY(-self.properties['elevation']) geomnode.setP(int(self.properties['inclination'])-360) geomnode.setTexture(tex) geomnode.setTransparency(TransparencyAttrib.MAlpha) geomnode.reparentTo(self.node) self.node.setR(self.properties['rotation'])
def __init__(self): ShowBase.__init__(self) self.win.setClearColor((0.455, 0.816, 0.945, 1)) self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "jump": 0, "action": 0 } # Mise en place des instructions self.title = addTitle("Project : 'Escape the forest'") self.inst1 = addInstructions(0.06, "[ECHAP]: Quit") self.inst2 = addInstructions(0.12, "[Left arrow]: Turn Freddy left") self.inst3 = addInstructions(0.18, "[Right arrow]: Turn Freddy right") self.inst4 = addInstructions(0.24, "[Top arrow]: Make Freddy move forward") self.inst5 = addInstructions(0.30, "Bottom arrow]: Make Freddy move back") self.inst6 = addInstructions(0.36, "[Space]: Make Freddy jump") self.inst7 = addInstructions(0.42, "[A]: Operate the lever") # 3D objects self.map = loader.loadModel("obj/Map.egg.pz") self.map.reparentTo(render) self.walls = loader.loadModel("obj/Wall.egg") self.walls.reparentTo(render) self.bridge = Actor("obj/Bridge.egg", {"Drop": "obj/Bridge.egg"}) self.bridge.reparentTo(render) self.bridge.pose("Drop", 0) self.lever = Actor("obj/Lever.egg", {"OnOff": "obj/Lever.egg"}) self.lever.reparentTo(render) self.lever.setPos(0, 12, 1) self.lever.pose("OnOff", 0) self.lever1 = Actor("obj/Lever.egg", {"OnOff": "obj/Lever.egg"}) self.lever1.reparentTo(render) self.lever1.setPos(50, 16, 1) self.lever1.pose("OnOff", 0) self.lever2 = Actor("obj/Lever.egg", {"OnOff": "obj/Lever.egg"}) self.lever2.reparentTo(render) self.lever2.setPos(22, 92, 1) self.lever2.pose("OnOff", 0) self.dirt = Actor("obj/Dirt.egg", {"Up": "obj/Dirt.egg"}) self.dirt.reparentTo(render) self.stone = Actor("obj/Stone.egg", {"Fall": "obj/Stone.egg"}) self.stone.reparentTo(render) # Creation of the main character, Freddy FreddyStartPos = (8, -8, 1.5) self.Freddy = Actor("obj/Freddy.egg", { "Run": "obj/Run.egg", "Pose": "obj/Pose.egg" }) self.Freddy.reparentTo(render) self.Freddy.setScale(1.4) self.Freddy.setPos(FreddyStartPos) self.Freddy.setH(180) winsound.PlaySound("sound/music.wav", winsound.SND_ASYNC) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.Freddy) self.floater.setZ(0) # Controls for move and interact self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("space", self.setKey, ["jump", True]) self.accept("a", self.setKey, ["action", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("space-up", self.setKey, ["jump", False]) self.accept("a-up", self.setKey, ["action", False]) taskMgr.add(self.movement, "Movement") self.moving = False self.disableMouse() ambientLight = AmbientLight("ambientLight") ambientLight.setColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) # Collisions self.cTrav = CollisionTraverser() self.pusher = CollisionHandlerPusher() self.FreddyGroundHandler = CollisionHandlerQueue() self.FreddyGroundSphere = CollisionSphere( 0, 0, 0.5, 0.3) #Coordinates of the center and radius self.FreddyGroundCol = CollisionNode('freddySphere') self.FreddyGroundCol.addSolid(self.FreddyGroundSphere) self.FreddyGroundCol.setFromCollideMask(BitMask32.bit(0)) self.FreddyGroundCol.setIntoCollideMask(BitMask32.allOff()) self.FreddyGroundColNp = self.Freddy.attachNewNode( self.FreddyGroundCol) self.cTrav.addCollider(self.FreddyGroundColNp, self.FreddyGroundHandler) self.BridgeHandler = CollisionHandlerQueue() self.BridgeBox = CollisionBox((1, 17, 0), (5, 16.8, 10)) self.BridgeCol = CollisionNode('bridgeBox') self.BridgeCol.addSolid(self.BridgeBox) self.BridgeCol.setFromCollideMask(BitMask32.allOff()) self.BridgeCol.setIntoCollideMask(BitMask32.bit(0)) self.BridgeColNp = self.bridge.attachNewNode(self.BridgeCol) self.cTrav.addCollider(self.BridgeColNp, self.BridgeHandler) self.pusher.addCollider(self.FreddyGroundColNp, self.BridgeColNp) self.StoneHandler = CollisionHandlerQueue() self.StoneBox = CollisionBox((39, 27, 0), (41, 31, 3)) self.StoneCol = CollisionNode('stoneBox') self.StoneCol.addSolid(self.StoneBox) self.StoneCol.setFromCollideMask(BitMask32.allOff()) self.StoneCol.setIntoCollideMask(BitMask32.bit(0)) self.StoneColNp = self.stone.attachNewNode(self.StoneCol) self.cTrav.addCollider(self.StoneColNp, self.StoneHandler) self.pusher.addCollider(self.FreddyGroundColNp, self.StoneColNp) self.DirtHandler = CollisionHandlerQueue() self.DirtBox = CollisionBox((15, 83, 0), (13, 82.5, 5)) self.DirtCol = CollisionNode('dirtBox') self.DirtCol.addSolid(self.DirtBox) self.DirtCol.setFromCollideMask(BitMask32.allOff()) self.DirtCol.setIntoCollideMask(BitMask32.bit(0)) self.DirtColNp = self.dirt.attachNewNode(self.DirtCol) self.cTrav.addCollider(self.DirtColNp, self.DirtHandler) self.pusher.addCollider(self.FreddyGroundColNp, self.DirtColNp)
def setup(self): self.worldNP = render.attachNewNode('World') self.distance_text = OnscreenText( text='Distance=0', pos=(0.75, 0.85), scale=0.08, mayChange=1) #Directxxxxxx(distance='Distance=%d'%(0)) self.speed_text = OnscreenText( text='Speed=0', pos=(0.75, 0.78), scale=0.08, mayChange=1) #Directxxxxxx(distance='Distance=%d'%(0)) self.time_text = OnscreenText( text='TotalTime=0', pos=(0.75, 0.71), scale=0.08, mayChange=1) #Directxxxxxx(distance='Distance=%d'%(0)) #self.time_maxsteer_text = OnscreenText(text='TotalTimeMaxSteer=0', pos = (0.85,0.70), scale = 0.05, mayChange=1)#Directxxxxxx(distance='Distance=%d'%(0)) #self.nn_image = OnscreenImage(image='blank.png', pos= (0.85,0,0.15), scale=0.45) # http://dev-wiki.gestureworks.com/index.php/GestureWorksCore:Python_%26_Panda3D:_Getting_Started_II_(Hello_Multitouch)#8._Create_a_method_to_draw_touchpoint_data self.total_time = 0. self.time_max_steering = 0. # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) #terrain = GeoMipTerrain("mySimpleTerrain") #terrain.setHeightfield("./models/heightfield_2.png") #terrain.getRoot().reparentTo(self.worldNP)#render) #terrain.generate() # Plane shape = BulletPlaneShape(Vec3(0, 0, 1), 0) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) np.node().addShape(shape) np.setPos(0, 0, -1) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) #np = self.worldNP.attachNewNode(BulletRigidBodyNode('Track')) #np.node().setMass(5000.0) #np.setPos(3, 0, 10) #np.setCollideMask(BitMask32.allOn())#(0x0f)) #self.track = BulletVehicle(self.world, np.node()) #self.track.setCoordinateSystem(ZUp) self.track_np = loader.loadModel( 'models/race_track_2.egg' ) # https://discourse.panda3d.org/t/panda3d-and-bullet-physics/15724/10 self.track_np.setPos(-72, -7, -3.5) self.track_np.setScale(10) self.track_np.reparentTo(render) self.track_np.setCollideMask(BitMask32.allOn()) #(0))#.allOn()) self.world.attachRigidBody(np.node()) self.track_np = np #self.track_np.show() # Chassis shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5)) ts = TransformState.makePos(Point3(0, 0, 0.5)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle')) np.node().addShape(shape, ts) np.setPos(0, 0, 0.05) np.node().setMass(800.0) np.node().setDeactivationEnabled(False) self.world.attachRigidBody(np.node()) #np.node().setCcdSweptSphereRadius(1.0) #np.node().setCcdMotionThreshold(1e-7) self.cTrav = CollisionTraverser() # Vehicle self.vehicle = BulletVehicle(self.world, np.node()) self.vehicle.setCoordinateSystem(ZUp) self.yugoNP = loader.loadModel('models/yugo/yugo.egg') self.yugoNP.setCollideMask(BitMask32(0)) #.allOn()) self.yugoNP.reparentTo(np) self.colHandler = CollisionHandlerQueue() # travel distance self.distance = 0. """self.sphere = CollisionSphere(0,0,0,2) self.sphere_col = CollisionNode('yugo') self.sphere_col.addSolid(self.sphere) self.sphere_col.setFromCollideMask(BitMask32.allOn()) self.sphere_col_np = self.yugoNP.attachNewNode(self.sphere_col) self.cTrav.addCollider(self.sphere_col_np,self.colHandler) self.sphere_col_np.show()""" self.yugo_col = CollisionNode('yugo_box') self.yugo_col.addSolid(CollisionBox(Point3(0, 0, 0.7), 0.9, 1.6, 0.05)) self.yugo_col.setFromCollideMask(BitMask32(1)) self.box_col_np = self.yugoNP.attachNewNode(self.yugo_col) self.cTrav.addCollider(self.box_col_np, self.colHandler) self.box_col_np.show() self.ray_col_np = {} self.ray_col_vec_dict = {} self.n_rays = self.model.shape[0] for i, ray_dir in enumerate( numpy.linspace(-numpy.pi / 4, numpy.pi / 4, self.n_rays)): # populate collision rays #print(ray_dir) self.ray = CollisionRay() y_dir, x_dir = numpy.cos(ray_dir), numpy.sin(ray_dir) self.ray.setOrigin(1.3 * x_dir, 1.3 * y_dir, 0.5) self.ray.setDirection(x_dir, y_dir, 0) self.ray_col = CollisionNode('ray%d' % (i)) self.ray_col.addSolid(self.ray) self.ray_col.setFromCollideMask( BitMask32.allOn()) #(0x0f))#CollideMask.bit(0) #self.ray_col.setIntoCollideMask(CollideMask.allOff()) self.ray_col_np['ray%d' % (i)] = self.yugoNP.attachNewNode( self.ray_col) self.cTrav.addCollider(self.ray_col_np['ray%d' % (i)], self.colHandler) self.ray_col_np['ray%d' % (i)].show() self.ray_col_vec_dict['ray%d' % (i)] = [] self.world.attachVehicle(self.vehicle) self.cTrav.showCollisions(render) # FIXME base.camera.reparentTo(self.yugoNP) # Right front wheel np = loader.loadModel('models/yugo/yugotireR.egg') np.reparentTo(self.worldNP) self.addWheel(Point3(0.70, 1.05, 0.3), True, np) # Left front wheel np = loader.loadModel('models/yugo/yugotireL.egg') np.reparentTo(self.worldNP) self.addWheel(Point3(-0.70, 1.05, 0.3), True, np) # Right rear wheel np = loader.loadModel('models/yugo/yugotireR.egg') np.reparentTo(self.worldNP) self.addWheel(Point3(0.70, -1.05, 0.3), False, np) # Left rear wheel np = loader.loadModel('models/yugo/yugotireL.egg') np.reparentTo(self.worldNP) self.addWheel(Point3(-0.70, -1.05, 0.3), False, np) # Steering info self.steering = 0.0 # degree self.steeringClamp = 38.0 #45.0 # degree self.steeringIncrement = 105.0 #120.0 # degree per second # add previous positions self.prevPos = [] self.prevPos.append(self.yugoNP.getPos(render)) self.model_offset = 0.5 if self.model.activation == 'relu' else 0. # Box """ for i,j in [(0,8),(-3,5),(6,-5),(8,3),(-4,-4),(0,0)]: shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) # https://discourse.panda3d.org/t/wall-collision-help/23606 np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(i, j, 2) np.setCollideMask(BitMask32.allOn())#(0x0f)) self.world.attachRigidBody(np.node()) self.boxNP = np #self.colHandler2 = CollisionHandlerQueue() visualNP = loader.loadModel('models/box.egg') visualNP.reparentTo(self.boxNP) #self.cTrav.addCollider(self.boxNP,self.colHandler) """ """ aNode = CollisionNode("TheRay") self.ray = CollisionRay() self.ray.setOrigin( self.yugoNP.getPos() ) self.ray.setDirection( Vec3(0, 10, 0) ) #self.ray.show() aNodePath = self.yugoNP.attachNewNode( CollisionNode("TheRay") ) aNodePath.node().addSolid(self.ray) aNodePath.show() """ #aNode.addSolid(self.ray) #self.ray = CollisionRay(0,0,0,10,0,0) #self.ray.reparentTo(self.yugoNP) #self.rayColl = CollisionNode('PlayerRay') #self.rayColl.addSolid(self.ray) #self.playerRayNode = self.yugoNP.attachNewNode( self.rayColl ) #self.playerRayNode.show() #base.myTraverser.addCollider (self.playerRayNode, base.floor) #base.floor.addCollider( self.playerRayNode, self.yugoNP) """
def __init__(self, base): DirectObject.__init__(self) self.base = base self.lastUpdate = 0.0 # Parameters self.wheelBaseOffset = 3.4 self.wheelSideOffset = 3.1 self.speedMax = 50.0 self.steerAngleMax = 20.0 self.numSensors = 15 self.sensorHeight = 2.0 # Load car model self.car = self.base.loader.loadModel("models/carBody") carCollider = self.car.attachNewNode(CollisionNode("carCollider")) carCollider.node().addSolid( CollisionBox(Point3(0.0, 0.0, 4.5), 6.0, 3.0, 3.5)) carCollider.setCollideMask(BitMask32(0)) carCollider.show() self.car.reparentTo(self.base.render) self.wheelFrontLeft = self.base.loader.loadModel("models/carWheel") self.wheelFrontLeft.reparentTo(self.car) self.wheelFrontLeft.setX(self.wheelBaseOffset) self.wheelFrontLeft.setY(self.wheelSideOffset) self.wheelFrontRight = self.base.loader.loadModel("models/carWheel") self.wheelFrontRight.reparentTo(self.car) self.wheelFrontRight.setX(self.wheelBaseOffset) self.wheelFrontRight.setY(-self.wheelSideOffset) self.wheelBackLeft = self.base.loader.loadModel("models/carWheel") self.wheelBackLeft.reparentTo(self.car) self.wheelBackLeft.setX(-self.wheelBaseOffset) self.wheelBackLeft.setY(self.wheelSideOffset) self.wheelBackRight = self.base.loader.loadModel("models/carWheel") self.wheelBackRight.reparentTo(self.car) self.wheelBackRight.setX(-self.wheelBaseOffset) self.wheelBackRight.setY(-self.wheelSideOffset) # Car properties self.steerAngle = 0.0 self.speed = 0.0 self.wheelFront = Vec3(1.0, 0.0, 0.0) * self.wheelBaseOffset self.wheelBack = Vec3(-1.0, 0.0, 0.0) * self.wheelBaseOffset self.initSensors(self.numSensors, self.sensorHeight) # Controls self.arrowUpDown = False self.arrowLeftDown = False self.arrowRightDown = False self.accept("arrow_up", self.onUpArrow, [True]) self.accept("arrow_up-up", self.onUpArrow, [False]) self.accept("arrow_left", self.onLeftArrow, [True]) self.accept("arrow_left-up", self.onLeftArrow, [False]) self.accept("arrow_right", self.onRightArrow, [True]) self.accept("arrow_right-up", self.onRightArrow, [False]) self.base.taskMgr.add(self.updateCar, "UpdateCarTask", priority=3) # DEBUG self.accept("d", self.debugOutput)
def __init__(self, initor, cdtype="triangles", mass=.3, restitution=0, allow_deactivation=False, allow_ccd=True, friction=.2, dynamic=True, name="rbd"): """ TODO: triangles do not seem to work (very slow) in the github version (20210418) Use convex if possible :param initor: could be itself (copy), or an instance of collision model :param type: triangle or convex :param mass: :param restitution: bounce parameter :param friction: :param dynamic: only applicable to triangle type, if an object does not move with force, it is not dynamic :param name: author: weiwei date: 20190626, 20201119 """ super().__init__(name) if isinstance(initor, gm.GeometricModel): if initor._objtrm is None: raise ValueError("Only applicable to models with a trimesh!") self.com = initor.objtrm.center_mass * base.physics_scale self.setMass(mass) self.setRestitution(restitution) self.setFriction(friction) self.setLinearDamping(.3) self.setAngularDamping(.3) if allow_deactivation: self.setDeactivationEnabled(True) self.setLinearSleepThreshold(.01 * base.physics_scale) self.setAngularSleepThreshold(.01 * base.physics_scale) else: self.setDeactivationEnabled(False) if allow_ccd: # continuous collision detection self.setCcdMotionThreshold(1e-7) self.setCcdSweptSphereRadius(0.0005 * base.physics_scale) geom_np = initor.objpdnp.getChild(0).find("+GeomNode") geom = copy.deepcopy(geom_np.node().getGeom(0)) vdata = geom.modifyVertexData() vertices = copy.deepcopy( np.frombuffer(vdata.modifyArrayHandle(0).getData(), dtype=np.float32)) vertices.shape = (-1, 6) vertices[:, :3] = vertices[:, :3] * base.physics_scale - self.com vdata.modifyArrayHandle(0).setData( vertices.astype(np.float32).tobytes()) geomtf = geom_np.getTransform() geomtf = geomtf.setPos(geomtf.getPos() * base.physics_scale) if cdtype == "triangles": geombmesh = BulletTriangleMesh() geombmesh.addGeom(geom) bulletshape = BulletTriangleMeshShape(geombmesh, dynamic=dynamic) bulletshape.setMargin(1e-6) self.addShape(bulletshape, geomtf) elif cdtype == "convex": bulletshape = BulletConvexHullShape( ) # TODO: compute a convex hull? bulletshape.addGeom(geom, geomtf) bulletshape.setMargin(1e-6) self.addShape(bulletshape, geomtf) elif cdtype == 'box': minx = min(vertices[:, 0]) miny = min(vertices[:, 1]) minz = min(vertices[:, 2]) maxx = max(vertices[:, 0]) maxy = max(vertices[:, 1]) maxz = max(vertices[:, 2]) pcd_box = CollisionBox(Point3(minx, miny, minz), Point3(maxx, maxy, maxz)) bulletshape = BulletBoxShape.makeFromSolid(pcd_box) bulletshape.setMargin(1e-6) self.addShape(bulletshape, geomtf) else: raise NotImplementedError pd_homomat = geomtf.getMat() pd_com_pos = pd_homomat.xformPoint( Vec3(self.com[0], self.com[1], self.com[2])) np_homomat = dh.pdmat4_to_npmat4(pd_homomat) np_com_pos = dh.pdv3_to_npv3(pd_com_pos) np_homomat[:3, 3] = np_com_pos # update center to com self.setTransform( TransformState.makeMat(dh.npmat4_to_pdmat4(np_homomat))) elif isinstance(initor, BDBody): self.com = initor.com.copy() self.setMass(initor.getMass()) self.setRestitution(initor.restitution) self.setFriction(initor.friction) self.setLinearDamping(.3) self.setAngularDamping(.3) if allow_deactivation: self.setDeactivationEnabled(True) self.setLinearSleepThreshold(.01 * base.physics_scale) self.setAngularSleepThreshold(.01 * base.physics_scale) else: self.setDeactivationEnabled(False) if allow_ccd: self.setCcdMotionThreshold(1e-7) self.setCcdSweptSphereRadius(0.0005 * base.physics_scale) np_homomat = copy.deepcopy(initor.get_homomat()) np_homomat[:3, 3] = np_homomat[:3, 3] * base.physics_scale self.setTransform( TransformState.makeMat(dh.npmat4_to_pdmat4(np_homomat))) self.addShape(initor.getShape(0), initor.getShapeTransform(0))
def _torso_combined_cdnp(name, radius): collision_node = CollisionNode(name) collision_primitive_c2 = CollisionBox(Point3(0.195, 0.0, 0.1704), x=.085 + radius, y=.101 + radius, z=.09 + radius) collision_node.addSolid(collision_primitive_c2) return collision_node
def __init__(self, img_size=512, screen_off=True, target_area_radius=5, initial_area_radius=10, keyboard_input=False, random_reset_around_target=False, test=False): logging.info('random_reset_around_target :%s', random_reset_around_target) self.random_reset_around_target = random_reset_around_target self.keyboard_input = keyboard_input # Configure the parallax mapping settings (these are just the defaults) self.img_size = img_size self.initial_area_radius = initial_area_radius self.target_area_radius = target_area_radius loadPrcFileData("", "side-by-side-stereo 1") if test: loadPrcFileData("", "load-display p3tinydisplay") loadPrcFileData("", "transform-cache false") loadPrcFileData("", "audio-library-name null") # Prevent ALSA errors loadPrcFileData("", "win-size %d %d" % (2 * img_size, img_size)) loadPrcFileData("", "parallax-mapping-samples 3\n" "parallax-mapping-scale 0.1") if screen_off: # Spawn an offscreen buffer loadPrcFileData("", "window-type offscreen") # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0} # Load the 'abstract room' model. This is a model of an # empty room containing a pillar, a pyramid, and a bunch # of exaggeratedly bumpy textures. self.room = loader.loadModel("models/abstractroom") self.room.reparentTo(render) # Create the main character, Ralph ghost = BulletGhostNode('Ghost') ghostNP = render.attachNewNode(ghost) # self.agent = Actor("models/agent", # {"run": "models/agent-run", # "walk": "models/agent-walk"}) self.agent = ghostNP self.agent.reparentTo(render) # self.agent.setScale(.2) target = BulletGhostNode('target') self.navigation_target = render.attachNewNode(target) self.navigation_target.reparentTo(render) # knghit=Knight((0,0,0),(0.3,.3,.3,1)) self.pieces = [Piece(self.room) for _ in range(200)] ################################################## cnodePath = self.room.attachNewNode(CollisionNode('room')) plane = CollisionPlane(Plane(Vec3(1, 0, 0), Point3(-60, 0, 0))) # left cnodePath.node().addSolid(plane) plane = CollisionPlane( Plane(Vec3(-1, 0, 0), Point3(60, 0, 0))) # right cnodePath.node().addSolid(plane) plane = CollisionPlane(Plane(Vec3(0, 1, 0), Point3(0, -60, 0))) # back cnodePath.node().addSolid(plane) plane = CollisionPlane( Plane(Vec3(0, -1, 0), Point3(0, 60, 0))) # front cnodePath.node().addSolid(plane) sphere = CollisionSphere(-25, -25, 0, 12.5) # tube = CollisionTube(-25, -25,0 , -25, -25, 1, 12.5) cnodePath.node().addSolid(sphere) box = CollisionBox(Point3(5, 5, 0), Point3(45, 45, 10)) cnodePath.node().addSolid(box) # cnodePath.show() # Make the mouse invisible, turn off normal mouse controls self.disableMouse() # props = WindowProperties() # props.setCursorHidden(True) # self.win.requestProperties(props) # self.camLens.setFov(60) self.camLens.setFov(80) # Set the current viewing target self.focus = LVector3(55, -55, 20) self.heading = 180 self.pitch = 0 self.mousex = 0 self.mousey = 0 self.last = 0 self.mousebtn = [0, 0, 0] # Start the camera control task: # taskMgr.add(self.controlCamera, "camera-task") # self.accept("escape", sys.exit, [0]) # self.accept("enter", self.toggleShader) # self.accept("j", self.rotateLight, [-1]) # self.accept("k", self.rotateLight, [1]) # self.accept("arrow_left", self.rotateCam, [-1]) # self.accept("arrow_right", self.rotateCam, [1]) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) # Add a light to the scene. self.lightpivot = render.attachNewNode("lightpivot") self.lightpivot.setPos(0, 0, 25) self.lightpivot.hprInterval(10, LPoint3(360, 0, 0)).loop() plight = PointLight('plight') plight.setColor((5, 5, 5, 1)) plight.setAttenuation(LVector3(0.7, 0.05, 0)) plnp = self.lightpivot.attachNewNode(plight) plnp.setPos(45, 0, 0) self.room.setLight(plnp) # Add an ambient light alight = AmbientLight('alight') alight.setColor((0.2, 0.2, 0.2, 1)) alnp = render.attachNewNode(alight) self.room.setLight(alnp) # Create a sphere to denote the light sphere = loader.loadModel("models/icosphere") sphere.reparentTo(plnp) # self.cameraModel = self.agent # self.win2 = self.openWindow() # self.win2.removeAllDisplayRegions() # self.dr2 = self.win2.makeDisplayRegion() # camNode = Camera('cam') # camNP = NodePath(camNode) # camNP.reparentTo(self.cameraModel) # camNP.setZ(150) # camNP.lookAt(self.cameraModel) # self.dr2.setCamera(camNP) # self.cam2 = camNP # Camera('cam')p # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above agent's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() cs = CollisionSphere(0, 0, 0, 0.2) cnodePath = self.agent.attachNewNode(CollisionNode('agent')) cnodePath.node().addSolid(cs) # cnodePath.show() self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(cnodePath, self.ralphGroundHandler) cnodePath = self.navigation_target.attachNewNode( CollisionNode('target')) cnodePath.node().addSolid(CollisionSphere(0, 0, 0, 2)) self.cTrav.addCollider(cnodePath, self.ralphGroundHandler) # Tell Panda that it should generate shaders performing per-pixel # lighting for the room. self.room.setShaderAuto() self.shaderenable = 1 # tex = self.win.getScreenshot() # tex.setFormat(Texture.FDepthComponent) tex = Texture() self.depthmap = tex tex.setFormat(Texture.FDepthComponent) altBuffer = self.win.makeTextureBuffer( "hello", img_size, img_size, tex, True) self.altBuffer = altBuffer altCam = self.makeCamera(altBuffer) altCam.reparentTo(self.agent) # altRender) altCam.setZ(0.4) l = altCam.node().getLens() l.setFov(80) l.setNear(.1) camera.reparentTo(self.agent) camera.setZ(0.4) l = self.camLens # l.setFov(80) l.setNear(.1)
def __init__(self): ShowBase.__init__(self) self.grid = np.loadtxt("input/maze.txt") f = open("input/start_point.txt", "r") self.start_pos = eval(f.read()) if FULLSCREEN: wp = WindowProperties() wp.setFullscreen(True) base.win.requestProperties(wp) self.disableMouse() self.accept("escape", sys.exit) self.camera.setPosHpr(self.start_pos[0], self.start_pos[1], CAMERA_SCALE, 0, -90, 0) # maze wall offset = 0.05 # expand collision boundaries for the walls for i in range(-1, len(self.grid) + 1): for j in range(-1, len(self.grid[0]) + 1): if i == -1 or j == -1 or i == len(self.grid) or j == len( self.grid[0]) or self.grid[i][j]: #box-1_-1 is not a valid name so we change it to boxa_b texti = i textj = j if i == -1: texti = 'a' if j == -1: textj = 'b' suffix = str(texti) + "_" + str(textj) # model exec("self.box" + suffix + " = self.loader.loadModel('models/cube')") exec("self.box" + suffix + ".reparentTo(self.render)") exec("self.box" + suffix + ".setPos(" + str(i) + ", " + str(j) + ", 1)") # collision node exec("self.boxCollider" + suffix + " = self.box" + suffix + ".attachNewNode(CollisionNode('wall_collide'))") exec( "self.boxCollider" + suffix + ".node().addSolid(CollisionBox(Point3(0-offset,0-offset,0-offset),Point3(1+offset,1+offset,1+offset)))" ) exec("self.boxCollider" + suffix + ".node().setIntoCollideMask(BitMask32.bit(0))") #exec("self.boxCollider" + suffix + ".show()") # maze ground model self.maze = loader.loadModel("models/cube") self.maze.setScale(len(self.grid), len(self.grid[0]), 1) self.maze.reparentTo(self.render) # maze ground collision node self.walls = self.maze.attachNewNode(CollisionNode('wall_collide')) self.walls.node().addSolid( CollisionBox(Point3(0, 0, 0), Point3(1, 1, 1))) self.walls.node().setIntoCollideMask(BitMask32.bit(1)) # maze ground plane collision node self.mazeGround = self.maze.attachNewNode( CollisionNode('ground_collide')) self.mazeGround.node().addSolid( CollisionPlane(Plane(Vec3(0, 0, 1), Point3(2, 2, 1)))) self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1)) # ball model self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # ball material m = Material() m.setSpecular((1, 1, 1, 1)) m.setShininess(96) self.ball.setMaterial(m, 1) # ball collision node self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) # collision ray self.ballGroundRay = CollisionRay() self.ballGroundRay.setOrigin(0, 0, 10) self.ballGroundRay.setDirection(0, 0, -1) # ray collision node self.ballGroundCol = CollisionNode('groundRay') self.ballGroundCol.addSolid(self.ballGroundRay) self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) # ray self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # collision traverser and handler queue self.cHandler = CollisionHandlerQueue() self.cTrav = CollisionTraverser() self.cTrav.addCollider(self.ballSphere, self.cHandler) self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # visual effects ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -1)) directionalLight.setColor((0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) self.start()
def run(self, root_node, restart_scene_cb): self.restart_scene_cb = restart_scene_cb self.root_node = root_node self.base.accept("escape", sys.exit) # Escape quits self.base.camera.set_pos(0, 0, 90) self.base.camera.set_hpr(0, -90, 0) self.score = Scores(self.game_end, self.game_quit_cb, self.restart_game) self.game_ended = False lens = OrthographicLens() lens.set_film_size(40 * win_aspect, 40) self.base.cam.node().setLens(lens) self.gc = GameControls(self.base, self.move_player, mouse_magnitude=7) self.base.disable_mouse() # debug camera movement # self.fm = FlyMove(self) # self.camera.set_pos(-20, 0, 10) # self.camera.set_hpr(-90, -50, 0) self.base.cTrav = CollisionTraverser() self.coll_hand_event = CollisionHandlerEvent() self.coll_hand_event.addInPattern('into-%in') paddle_path = 'models/paddle' self.player_paddle = pp = self.load_and_render(paddle_path) pp.set_pos(-20, 0, 0) pp.set_hpr((90, 0, 0)) self.ai_paddle = aip = self.load_and_render(paddle_path, copy=True) aip.set_pos(20, 0, 0) aip.set_hpr((90, 0, 0)) self.ball = self.load_and_render('models/ball') collision_ball = CollisionSphere(0, 0, 0, 1) cnodePath = self.ball.attachNewNode(CollisionNode('ball')) cnodePath.node().addSolid(collision_ball) self.base.cTrav.add_collider(cnodePath, self.coll_hand_event) # ball movement self.reset_ball() self.ball_speed_scale = 0.30 self.base.task_mgr.add(self.ball_move_task, 'ball-move') # set up boundaries on the top and bottom self.border_distance = border_distance = 20 self.top_boundary = self.load_and_render(paddle_path, copy=True) self.top_boundary.set_sx(5) self.top_boundary.set_y(border_distance) self.bottom_boundary = self.load_and_render(paddle_path, copy=True) self.bottom_boundary.set_sx(5) self.bottom_boundary.set_y(-1 * border_distance) horizontal_distance = 30 self.player_side_plane = CollisionPlane( Plane(LVector3f(1, 0, 0), LPoint3f(-1 * horizontal_distance, 0, 0))) self.player_side_cnode = self.root_node.attachNewNode( CollisionNode('pplane')) self.player_side_cnode.node().add_solid(self.player_side_plane) self.ai_side_plane = CollisionPlane( Plane(LVector3f(-1, 0, 0), LPoint3f(horizontal_distance, 0, 0))) self.ai_side_cnode = self.root_node.attachNewNode( CollisionNode('aiplane')) self.ai_side_cnode.node().add_solid(self.ai_side_plane) # add collision to paddles and walls, everything the ball can reflect off of for np in [pp, aip, self.bottom_boundary, self.top_boundary]: cs = CollisionBox((0, 0, 0), 5, 0.25, 8) cnodePath = np.attachNewNode(CollisionNode('wall')) cnodePath.node().addSolid(cs) self.base.cTrav.add_collider(cnodePath, self.coll_hand_event) self.base.accept('into-wall', self.ball_collision) self.base.accept('into-pplane', self.player_side_goal) self.base.accept('into-aiplane', self.ai_side_goal) self.ai = PongAI(self.base, self.ai_paddle, self.ball, border_distance)