def mousePressed(self, event): print 'got mouse pressed event from', event.sender if (not self.enabled or event.modifiers.isDown(KeyboardButton.control())): print 'short circuiting' return shiftDown = event.modifiers.isDown(KeyboardButton.shift()) if event.sender == self.engine: if not shiftDown: self.deselectAll() else: self._setEditMode(event.modifiers.isDown(MouseButton.three())) node = event.sender if shiftDown: # Shift-clicking a node toggles its selected state. if node.isSelected(): self.selection.remove(node) node.setSelected(False) else: self.selection.append(node) node.setSelected(True) elif len(self.selection) == 1 and node.isSelected(): # This is already the only node selected. return else: print 'selecting', node self.deselectAll() node.setSelected(True) self.selection.append(node) if self.editMode: self.handle.setClients([NodePath(n) for n in self.selection], self.getSelectionCenter()) else: self.handle.setClients([])
def poll_keyboard(self, velocity): # under normal circumstances, use median of joytick output x_speed = 0.5 y_speed = 0.5 # checks keyboard, not mouse, in this case is_down = self.base.mouseWatcherNode.is_button_down # Instead of usual movement, exactly counteract joystick, # if using joystick and currently moving if self.joystick: if abs(velocity.x) > self.threshold: if velocity.x > 0: x_speed = velocity.x else: x_speed = -velocity.x if abs(velocity.y) > self.threshold: if velocity.y > 0: y_speed = velocity.y else: y_speed = -velocity.y else: velocity.x = 0 velocity.y = 0 if is_down(KeyboardButton.up()): velocity.y += y_speed if is_down(KeyboardButton.down()): velocity.y -= y_speed if is_down(KeyboardButton.left()): velocity.x -= x_speed # print 'keyboard' if is_down(KeyboardButton.right()): velocity.x += x_speed return velocity
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)
def __init__(self, base): self.base = base self.is_down = base.mouseWatcherNode.is_button_down self.forward_button = KeyboardButton.ascii_key(b'w') self.backward_button = KeyboardButton.ascii_key(b's') self.strafe_left_button = KeyboardButton.ascii_key(b'a') self.strafe_right_button = KeyboardButton.ascii_key(b'd')
def _saveLayout(self): if self.modButtons.isDown(KeyboardButton.control()): self.modButtons.buttonUp(KeyboardButton.control()) self.modButtons.buttonUp(KeyboardButton.asciiKey('s')) filename = asksaveasfilename(filetypes=[('plist files', '*.plist')]) if filename: self.layout.save(filename) AppPreferences.set('last_layout', filename)
def read_keys(self): self.upArrowIsPressed = base.mouseWatcherNode.isButtonDown( KeyboardButton.up()) self.downArrowIsPressed = base.mouseWatcherNode.isButtonDown( KeyboardButton.down()) self.rightArrowIsPressed = base.mouseWatcherNode.isButtonDown( KeyboardButton.right()) self.leftArrowIsPressed = base.mouseWatcherNode.isButtonDown( KeyboardButton.left())
def __init__(self): self.instructionText = addInstructions(0.95, '[ESC]: Leave Mouselook mode.') self.eventDispatcher = EventDispatcher() self.cameraMode = None self.clickPos = Vec2() self.lastMousePos = Vec2() self.focus = Vec3() self.mouseDown = False self.initialPos = Vec3() self.initialHpr = Vec3() self.initialMat = None # Disable the built-in mouse camera control (it sucks). base.disableMouse() self.setCameraMode(TRACKBALL) # Set the camera's initial position. base.camera.setPosHpr(0, 12, 30, 180, -70, 0) # Turn off events generated with modifier buttons, e.g. 'shift-a' # This is to keep keyboard control working after you alt-tab out # of the app. base.mouseWatcherNode.setModifierButtons(ModifierButtons()) base.buttonThrowers[0].node().setModifierButtons(ModifierButtons()) # This is a diagonal matrix that keeps track of movement key # state. The first three diagonal entries can be 1, 0, or -1. self.mouseLookTransMat = Mat4.scaleMat(Vec3(0.0, 0.0, 0.0)) # Keep track of how many movement keys are currently pressed. This # lets us short-circuit past a lot of math when no keys are held. self.keysHeld = 0 # Handle events for the movement keys. for key, value in key2MatArgs.items(): self.accept(key, self._moveKeyHandler, value) self.accept('escape', self._escKeyHandler) self.accept('m', self._mKeyHandler) self.accept('mouse1', self._mouseDownHandler, [1]) self.accept('mouse1-up', self._mouseUpHandler, [1]) self.accept('mouse2', self._mouseDownHandler, [2]) self.accept('mouse2-up', self._mouseUpHandler, [2]) self.accept('wheel_up', self._mouseWheelHandler, [1]) self.accept('wheel_down', self._mouseWheelHandler, [-1]) self.modButtons = ModifierButtons() self.modButtons.addButton(KeyboardButton.control()) self.accept('control', self.modButtons.buttonDown, [KeyboardButton.control()]) self.accept('control-up', self.modButtons.buttonUp, [KeyboardButton.control()]) self.accept(base.win.getWindowEvent(), self._windowHandler)
def _openLayout(self): if self.modButtons.isDown(KeyboardButton.control()): self.modButtons.buttonUp(KeyboardButton.control()) self.modButtons.buttonUp(KeyboardButton.asciiKey('o')) filename = askopenfilename(filetypes=[('plist files', '*.plist')]) if filename: if self.layout: NodePath(self.layout).detachNode() self.layout = MissionLayout.loadLayout(filename) render.attachNewNode(self.layout) AppPreferences.set('last_layout', filename)
def rotate_tree(task): global tree_root rot_speed = 360 / 3 dt = globalClock.dt turn = 0 if base.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key('a')): turn += rot_speed * dt if base.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key('d')): turn -= rot_speed * dt tree_root.set_h(tree_root, turn) return task.cont
def __init__(self): render.setAntialias(AntialiasAttrib.MAuto) # Enable physics - perhaps this should go someplace else, but it must # be done before the Vehicle is initialized. base.enableParticles() aei = AngularEulerIntegrator() base.physicsMgr.attachAngularIntegrator(aei) SelectionEngine.getDefault().enable() SelectionManager.getDefault().enable() # Make the environment and the vehicle model. makeEnvironment() self.vehicle = Vehicle(render) MissionElement.loadElementConfig('mission_elements.plist') #layoutName = AppPreferences.get('last_layout', 'defaultLayout.plist') if len(sys.argv) == 2: layoutName = sys.argv[1] print "Using command line argument %s for layout" %layoutName else: print "Using default layout file" print "Use ./sim2.py [layout file] to use a different layout" print "Or press Ctrl+O to open a new layout in the simulator" layoutName = 'defaultLayout.plist' self.layout = MissionLayout.loadLayout(layoutName) render.attachNewNode(self.layout) self.vehicle.setLayout(self.layout) #Link the layout # Set up render buffer viewer, to aide debugging. self.accept("v", base.bufferViewer.toggleEnable) self.accept("V", base.bufferViewer.toggleEnable) base.bufferViewer.setPosition("llcorner") # Set up file saver self.accept('s', self._saveLayout) self.accept('o', self._openLayout) self.accept('f', self._setFreq) root = Tk() root.withdraw() self.modButtons = ModifierButtons() self.modButtons.addButton(KeyboardButton.control()) self.accept('control', self.modButtons.buttonDown, [KeyboardButton.control()]) self.accept('control-up', self.modButtons.buttonUp, [KeyboardButton.control()]) # Add GUI Controls '''
def __init__(self): render.setAntialias(AntialiasAttrib.MAuto) # Enable physics - perhaps this should go someplace else, but it must # be done before the Vehicle is initialized. base.enableParticles() aei = AngularEulerIntegrator() base.physicsMgr.attachAngularIntegrator(aei) SelectionEngine.getDefault().enable() SelectionManager.getDefault().enable() # Make the environment and the vehicle model. makeEnvironment() self.vehicle = Vehicle(render) MissionElement.loadElementConfig('mission_elements.plist') #layoutName = AppPreferences.get('last_layout', 'defaultLayout.plist') if len(sys.argv) == 2: layoutName = sys.argv[1] print "Using command line argument %s for layout" % layoutName else: print "Using default layout file" print "Use ./sim2.py [layout file] to use a different layout" print "Or press Ctrl+O to open a new layout in the simulator" layoutName = 'defaultLayout.plist' self.layout = MissionLayout.loadLayout(layoutName) render.attachNewNode(self.layout) self.vehicle.setLayout(self.layout) #Link the layout # Set up render buffer viewer, to aide debugging. self.accept("v", base.bufferViewer.toggleEnable) self.accept("V", base.bufferViewer.toggleEnable) base.bufferViewer.setPosition("llcorner") # Set up file saver self.accept('s', self._saveLayout) self.accept('o', self._openLayout) self.accept('f', self._setFreq) root = Tk() root.withdraw() self.modButtons = ModifierButtons() self.modButtons.addButton(KeyboardButton.control()) self.accept('control', self.modButtons.buttonDown, [KeyboardButton.control()]) self.accept('control-up', self.modButtons.buttonUp, [KeyboardButton.control()]) # Add GUI Controls '''
def poll_keyboard(self): x_speed = 0.5 y_speed = 0.5 velocity = LVector3(0) # poorly named, checks keyboard, not mouse, in this case is_down = base.mouseWatcherNode.is_button_down if is_down(KeyboardButton.up()): velocity.y += y_speed if is_down(KeyboardButton.down()): velocity.y -= y_speed if is_down(KeyboardButton.left()): velocity.x -= x_speed if is_down(KeyboardButton.right()): velocity.x += x_speed return velocity
def camera_move(self, task): """ Moves the camera about the quadcopter """ keys_vs_moves = {'k': i, 'h': -i, 'i': j, 'y': -j, 'u': k, 'j': -k } mat = np.array(self.cam.getMat())[0:3, 0:3] move_total = LPoint3f(0, 0, 0) for key, move in keys_vs_moves.items(): pressed_key = self.mouseWatcherNode.is_button_down(KeyboardButton.asciiKey(key)) if pressed_key: move = LPoint3f(move) move_total += move # if any([abs(coordinate) > 0 for coordinate in move_total]): # ROTATE COORDINATE SYSTEM (TO CAMERA) move_total = LPoint3f(*tuple(np.dot(mat.T, np.array(move_total)))) proportionality_constant = 0.05 cam_pos = self.cam.getPos() + move_total * proportionality_constant self.cam.setPos(cam_pos) self.cam.lookAt(self.quad_model) return task.cont
def update(self, entities_by_filter): start_balls = base.mouseWatcherNode.is_button_down( KeyboardButton.space(), ) if start_balls: for entity in set(entities_by_filter['ball']): entity.remove_component(Resting) entity.add_component(Movement(value=Vec3(-1, 0, 0)))
def keystroke(self, key): key = str(KeyboardButton.asciiKey(key)) if key == None: return if key == 'space': key = ' ' if len(key) != 1: return if not application.paused: if hasattr(__main__, 'keystroke'): __main__.keystroke(key) for entity in scene.entities: if entity.enabled == False or entity.ignore or entity.ignore_input: continue if application.paused and entity.ignore_paused == False: continue if hasattr(entity, 'keystroke') and callable(entity.keystroke): entity.keystroke(key) if hasattr(entity, 'scripts'): for script in entity.scripts: if script.enabled and hasattr(script, 'keystroke') and callable( script.keystroke): script.keystroke(key)
class StartBallMotion(System): """ StartBallMotion ensures that the game restarts after the start key is pressed. """ entity_filters = { 'ball': and_filter([ Proxy('model'), Resting, Ball, ]), } start_key = KeyboardButton.space() def update(self, entities_by_filter): """ Check whether the resting ball should be started? Note that restarting the ball's movement means removing the Entity's Resting Component, and adding it's Movement component with the desired direction. """ start_key_is_pressed = base.mouseWatcherNode.is_button_down( StartBallMotion.start_key) if start_key_is_pressed: for entity in set(entities_by_filter['ball']): del entity[Resting] entity[Movement] = Movement( direction=Vec3(-0.1 * randrange(5, 10), 0, 0))
def acceptMovement(self): # accept movement (x, y, z) = self.camera.getPos() (dx, dy, dz) = self.cameraSpeed (newX, newY, newZ) = (x + dx, y + dy, z + dz) forward_button = KeyboardButton.ascii_key('w') backward_button = KeyboardButton.ascii_key('s') leftward_button = KeyboardButton.ascii_key('a') rightward_button = KeyboardButton.ascii_key('d') # next line is from panda3D website is_down = self.mouseWatcherNode.is_button_down if is_down(forward_button): self.accForward() elif is_down(backward_button): self.accBackward() elif is_down(leftward_button): self.accLeftward() elif is_down(rightward_button): self.accRightward() else: self.cameraSpeed = (0, 0, dz)
def __init__(self): self.panra = 1 self.pwa = KeyboardButton.ascii_key("w") self.sano = Actor("HailPar.egg", {"Anaib": "Sbig-Armsjin"}) self.thago = threading.Thread(target=self.run) self.thago.start() self.sano.reparentTo(render)
def onMouseMoveTransforming3D(self, vp): now = self.getPointOnGizmo() gizmoOrigin = self.getGizmoOrigin() gizmoDir = self.getGizmoDirection(self.widget.activeAxis.axisIdx) ref = Vec3.forward() if gizmoDir == ref: ref = Vec3.right() nowVec = Vec3(now - gizmoOrigin).normalized() origVec = Vec3(self.transformStart - gizmoOrigin).normalized() axisToHprAxis = { 0: 1, # pitch 1: 2, # roll 2: 0 # yaw } snap = not vp.mouseWatcher.isButtonDown(KeyboardButton.shift()) origAngle = origVec.signedAngleDeg( ref, self.getGizmoDirection(self.widget.activeAxis.axisIdx)) angle = nowVec.signedAngleDeg( ref, self.getGizmoDirection(self.widget.activeAxis.axisIdx)) hpr = Vec3(0) if snap: ang = round(-(angle - origAngle) / 15) * 15 else: ang = -(angle - origAngle) hpr[axisToHprAxis[self.widget.activeAxis.axisIdx]] = ang self.toolVisRoot.setHpr(hpr)
def update_thruster(self, task): heating = 0.33 cooling = 0.04 thruster_ramp_time = 0.4 thrusting = base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key(b's'), ) overheated = self.thruster_heat > 1.0 if overheated and not self.overheated: self.thruster_overheat_sound.play() self.overheated = overheated if thrusting and not overheated: self.thruster_power += (1 / thruster_ramp_time) * globalClock.dt else: self.thruster_power -= (1 / thruster_ramp_time) * globalClock.dt if self.thruster_power < 0.0: self.thruster_power = 0.0 if self.thruster_power > 1.0: self.thruster_power = 1.0 power = self.thruster_power self.thruster_heat += (-cooling * (1 - power) + heating * power) * globalClock.dt if self.thruster_heat < 0.0: self.thruster_heat = 0.0 self.thruster_sound.set_volume(self.thruster_power * 2) self.thruster_sound.set_play_rate(0.1 + ((random() / 50) + (self.thruster_power / 120))) self.thruster_heat_bar['value'] = self.thruster_heat * 100 self.thruster_heat_bar['text'] = "{:3.0f}%".format( self.thruster_power * 100, ) if self.thruster_heat > 1.0: self.thruster_heat_bar['barColor'] = (1, 1, 1, 1) else: self.thruster_heat_bar['barColor'] = (1, 0, 0, 1) return task.cont
def _dragStart(self, nodeFrame, event): # Mark this node as selected base.messenger.send("selectNode", [ self, True, base.mouseWatcherNode.isButtonDown(KeyboardButton.shift()), True ]) # tell everyone we started to drag this node base.messenger.send("dragNodeStart", [self]) # Remove any previous started drag tasks taskMgr.remove("dragNodeDropTask") # get some positions vWidget2render2d = nodeFrame.getPos(render2d) vMouse2render2d = Point3(0) if event is not None: # we get the mouse position from the event vMouse2render2d = Point3(event.getMouse()[0], 0, event.getMouse()[1]) else: # we try to get the current mouse position from the mouse watcher mwn = base.mouseWatcherNode if mwn.hasMouse(): vMouse2render2d = Point3(mwn.getMouse()[0], 0, mwn.getMouse()[1]) editVec = Vec3(vWidget2render2d - vMouse2render2d) self.hasMoved = False # Initiate the task to move the node and pass it some initial values t = taskMgr.add(self.dragTask, "dragNodeDropTask") t.nodeFrame = nodeFrame t.editVec = editVec t.mouseVec = vMouse2render2d
def acceptMovement(self): # accept movement (x, y, z) = self.camera.getPos() (dx, dy, dz) = self.cameraSpeed (newX, newY, newZ) = (x+dx, y+dy, z+dz) forward_button = KeyboardButton.ascii_key('w') backward_button = KeyboardButton.ascii_key('s') leftward_button = KeyboardButton.ascii_key('a') rightward_button = KeyboardButton.ascii_key('d') # next line is from panda3D website is_down = self.mouseWatcherNode.is_button_down if is_down(forward_button): self.accForward() elif is_down(backward_button): self.accBackward() elif is_down(leftward_button): self.accLeftward() elif is_down(rightward_button): self.accRightward() else: self.cameraSpeed = (0, 0, dz)
def __init__(self): #Modify the Panda3D config on-the-fly #In this case, edit the window title load_prc_file_data( "", """window-title PoultryGeist threading-model /Draw multisamples 2 framebuffer-multisample 1 """) # Construct and create the pipeline self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) self.width, self.height = (800, 600) render.setAntialias(AntialiasAttrib.MAuto) # Set the model quality, (low or high) self.quality = "low" print("[>] PoultryGeist:\t Setting Model Resolution to {}".format( self.quality.upper())) # Set the time self.render_pipeline.daytime_mgr.time = "20:15" # Turn off normal mouse controls self.disableMouse() # Hide the cursor props = WindowProperties() props.setCursorHidden(True) props.setMouseMode(WindowProperties.M_relative) # Lower the FOV to make the game more difficult self.win.requestProperties(props) self.camLens.setFov(90) # Register the buttons for movement self.w_button = KeyboardButton.ascii_key('w'.encode()) self.s_button = KeyboardButton.ascii_key('s'.encode()) self.switch_button = KeyboardButton.ascii_key('p'.encode()) # Initialise the SceneManager self.sceneMgr = SceneManager(self) # Add the sceneMgr events to run as a task taskMgr.add(self.sceneMgr.runSceneTasks, "scene-tasks")
def _mouseDownHandler(self, button): if base.mouseWatcherNode.hasMouse(): if button == 2 or self.modButtons.isDown(KeyboardButton.control()): self.clickPos = Vec2(base.mouseWatcherNode.getMouse()) self.mouseDown = True offset = self.focus - base.camera.getPos() self.initialTranslation = offset.length() self.initialHpr = base.camera.getHpr()
def __init__(self, base): self.base = base self.forward = KeyboardButton.ascii_key('w') self.backward = KeyboardButton.ascii_key('s') self.left = KeyboardButton.ascii_key('a') self.right = KeyboardButton.ascii_key('d') self.node = self.base.loader.loadModel(self.model_path) self.node.reparentTo(self.base.render) # set initial position # x, y, z self.set_pos(0, 15, -1) self.set_rot(20, 10, 0) # create a task to check for movement self.add_task(self.check_movement, 'detect_player_movement')
def __init__(self, game, character): self.game = game self.character = character # class properties self.buttons = { "forward": KeyboardButton.ascii_key("w"), "backward": KeyboardButton.ascii_key("s"), "left": KeyboardButton.ascii_key("a"), "right": KeyboardButton.ascii_key("d"), "sprint": KeyboardButton.shift(), } self.moved = False # start movement task taskMgr.add(self.move, "Player.move") taskMgr.doMethodLater(1.0 / Constants.TICKRATE, self.sendLoc, "Player.sendLoc")
def update(task): if s.mouseWatcherNode.is_button_down(KeyboardButton.up()): pingPong("accelerate", -1) elif s.mouseWatcherNode.is_button_down(KeyboardButton.down()): pingPong("accelerate", 1) else: pingPong("accelerate", 0) if s.mouseWatcherNode.is_button_down(KeyboardButton.right()): pingPong("turn", -1) elif s.mouseWatcherNode.is_button_down(KeyboardButton.left()): pingPong("turn", 1) else: pingPong("turn", 0) if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b'd')): pingPong("strafe", -1) elif s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b'a')): pingPong("strafe", 1) else: pingPong("strafe", 0) if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b's')): pingPong("hover", 1, 0, 0, 20) else: pingPong("hover", 0, 0, 0, 20) return task.cont
def update(self, entities_by_filter): # Should resting balls be started? start_key = KeyboardButton.space() start_balls = base.mouseWatcherNode.is_button_down(start_key) if start_balls: for entity in set(entities_by_filter['ball']): del entity[Resting] entity[Movement] = Movement(value=Vec3(-1, 0, 0))
def poll_keyboard(self): # under normal circumstances, use median of joytick output x_speed = 0.5 y_speed = 0.5 # checks keyboard, not mouse, in this case is_down = self.base.mouseWatcherNode.is_button_down if not self.joystick: self.velocity.x = 0 self.velocity.y = 0 if is_down(KeyboardButton.up()): self.velocity.y += y_speed if is_down(KeyboardButton.down()): self.velocity.y -= y_speed if is_down(KeyboardButton.left()): self.velocity.x -= x_speed # print 'keyboard' if is_down(KeyboardButton.right()): self.velocity.x += x_speed
def __init__(self, charNr): FSM.__init__(self, "FSM-Player%d"%charNr) charPath = "characters/character%d/" % charNr self.character = Actor( charPath + "char"#, { #"Idle":charPath + "idle", #"walk":charPath + "walk", #"punch_l":charPath + "punch_l", #"punch_r":charPath + "punch_r", #"kick_l":charPath + "kick_l", #"kick_r":charPath + "kick_r", #"defend":charPath + "defend" #} ) self.character.reparentTo(render) self.character.hide() self.walkSpeed = 5.0 # units per second self.leftButton = KeyboardButton.asciiKey('a') self.rightButton = KeyboardButton.asciiKey('d')
def update(self, entities_by_filter): left = 0 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key(b'w')): left += 1 if base.mouseWatcherNode.is_button_down( KeyboardButton.ascii_key(b's')): left -= 1 right = 0 if base.mouseWatcherNode.is_button_down(KeyboardButton.up()): right += 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.down()): right -= 1 for entity in entities_by_filter['paddle']: if entity.get_component(Paddle).player == 0: entity.get_component(Movement).value.z = left elif entity.get_component(Paddle).player == 1: entity.get_component(Movement).value.z = right
def update(task): global thrust if thrust > 0: thrust -= 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.space()): if thrust < 15: thrust += 2 for beam in beams: beam.setScale(thrust / 8) return task.cont
def select(self, event): modifiers = event.getModifierButtons() if modifiers.isDown(KeyboardButton.shift()): incr = -1 else: incr = 1 new_selection = self.current_selection + incr if new_selection < 0: new_selection = len(self.current_list) - 1 if new_selection >= len(self.current_list): new_selection = 0 self.current_selection = new_selection self.update_suggestions()
def move_camera(self, task): rot = globalClock.get_dt() * 360.0 / 3.0 up_down = 0 left_right = 0 if base.mouseWatcherNode.is_button_down(KeyboardButton.up()): up_down -= 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.down()): up_down += 1 if base.mouseWatcherNode.is_button_down(KeyboardButton.left()): left_right -=1 if base.mouseWatcherNode.is_button_down(KeyboardButton.right()): left_right +=1 if self.rotation_mode and base.mouseWatcherNode.has_mouse(): mouse_pos = base.mouseWatcherNode.get_mouse() mouse_delta = mouse_pos - self.mouse_pos self.mouse_pos = Point2(mouse_pos) up_down += mouse_delta.get_y() * 50 left_right += mouse_delta.get_x() * -50 self.camera_orbit.set_h(self.camera_orbit, left_right * rot) new_pitch = self.camera_pitch.get_p() + up_down * rot self.camera_pitch.set_p(min(max(new_pitch, -89), 89)) return Task.cont
def update(self, entities_by_filter): for entity in entities_by_filter['paddle']: paddle = entity[Paddle] movement = entity[Movement] # What keys does the player use? if paddle.player == Players.LEFT: up_key = KeyboardButton.ascii_key(b'w') down_key = KeyboardButton.ascii_key(b's') elif paddle.player == Players.RIGHT: up_key = KeyboardButton.up() down_key = KeyboardButton.down() # Read player input delta = 0 if base.mouseWatcherNode.is_button_down(up_key): delta += 1 if base.mouseWatcherNode.is_button_down(down_key): delta -= 1 # Store movement movement.value.z = delta
def __init__(self): # # MODEL AND ANIMATION # # The players model file path self.basePath = "character/" self.model = self.basePath + "character" # Paths of the animation files self.anim_idle = self.basePath + "character-Idle" self.anim_walk = self.basePath + "character-Walk" self.anim_plant = self.basePath + "character-Plant" # NOTE: This should always be enabled to smoth the transition within # animations. For example for the accleration of the character # untill it reaches full pace. self.enable_interpolation = True # # AUDIO # self.sfxPath = "sfx/" self.walk_sound = loader.loadSfx(self.sfxPath + "step.ogg") self.walk_sound.setLoop(True) # # CONTROLS # self.key_forward = KeyboardButton.asciiKey('w') self.key_backward = KeyboardButton.asciiKey('s') self.key_left = KeyboardButton.asciiKey('a') self.key_right = KeyboardButton.asciiKey('d') self.key_plant = KeyboardButton.space() self.key_center_camera = KeyboardButton.home() # accleration for the various states self.accleration = 3.5 # the speed of how fast the player deacclerates self.deaccleration = 16.0 # maximum acclerations at the various states self.max_accleration = 8.0 # the speed for how fast the player is generally moving self.speed = 0.7 # # GAME SPECIFIC # # planting possibility self.planting_enabled = False self.carry_seed = False # # CAMERA CONTROL VARIABLES # # Camera basics self.cam_near_clip = 0.5 self.cam_far_clip = 5000 self.cam_fov = 70 # Mouse camera movement # enables the camera control via the mouse self.enable_mouse = True # invert vertical camera movements self.mouse_invert_vertical = False # screen sizes self.win_width_half = base.win.getXSize() / 2 self.win_height_half = base.win.getYSize() / 2 # mouse speed self.mouse_speed_x = 150.0 self.mouse_speed_y = 80.0 # the next two vars will set the min and max distance the cam can have # to the node it is attached to self.max_cam_distance = 5.0 self.min_cam_distance = 2.0 # the initial cam distance self.cam_distance = (self.max_cam_distance - self.min_cam_distance) / 2.0 + self.min_cam_distance # the maximum distance on the Z-Axis to the player self.max_cam_height_distance = 2.0 # the minimum distance on the Z-Axis to the player self.min_cam_height_distance = 0.15 # the average camera height self.cam_height_avg = (self.max_cam_height_distance - self.min_cam_height_distance) / 2.0 + self.min_cam_height_distance # the initial cam height self.cam_height = self.cam_height_avg # the speed of the cameras justification movement towards # the average height self.cam_z_justification_speed = 1 # a floater which hovers over the player and is used as a # look at position for the camera self.cam_floater_pos = Point3F(0, 0, 1.5) # # PHYSICS # # show collision solids self.show_collisions = False # The physical physic_world which will be responsible for collision checks and # physic updates self.physic_world = None # the name of the collision solids that surround the character self.char_collision_name = "CharacterCollisions" # the mass of the character self.player_mass = 25 # the heights of the various player states # normal height self.player_height = 1.186 # the radius of the players collision shape self.player_radius = self.player_height / 4.0 # step height self.stepheight = 0.7
def __init__(self, mainWin=base.win, mainCam=base.cam, scene=render): self.lastMousePos = Vec2(-2, -2) self.lastId = 0 self.pressedNode = None self.mDownId = 0 self.idStack = range(1, 256) self.idTable = {} self.aspectRatio = 1 self.checkCursorTask = Task(self.checkCursor, 'checkCursorTask') self.enabled = True self.mouseListeners = [] self.mainCam = mainCam mainCam.node().setCameraMask(BitMask32(1)) tempnode = NodePath(PandaNode('temp node')) tempnode.setShaderAuto() tempnode.setShaderInput('hi_id', Vec4(0, 0, 0, 0), 2) mainCam.node().setInitialState(tempnode.getState()) # Set up a node with the silhouetteGen shader. We'll apply this node's # state to custom cameras below. tempnode.setShader(loader.loadShader('silhouetteGen.sha'), 100) tempnode.setShaderInput('hi_id', Vec4(0, 0, 0, 0), 0) tempnode.setAntialias(AntialiasAttrib.MNone, 100) tempnode.setBin('inactive', 0, 1) initialState = tempnode.getState() tempnode.setBin('opaque', 0, 1) selnodeState = tempnode.getState() # We'll be using this a few times, so make an easy name for it. mainLens = mainCam.node().getLens() # Set up a buffer to which we draw a silhouette of any geometry that # we want to outline. We draw the outline by applying a Sobel edge # detection shader to the contents of this buffer. silhouetteBuffer = mainWin.makeTextureBuffer('silhouetteBuffer', 0, 0) silhouetteBuffer.setClearColor(Vec4(0, 0, 0, 1)) self.silhouetteBuffer = silhouetteBuffer silhouetteCamera = base.makeCamera(silhouetteBuffer, lens=mainLens) silhouetteCamera.node().setScene(scene) silhouetteCamera.node().setInitialState(initialState) silhouetteCamera.node().setTagState('sel', selnodeState) silhouetteCamera.node().setTagStateKey('sel') silhouetteCamera.node().setCameraMask(BitMask32(8)) tempnode.setShader(loader.loadShader('mousePicker.sha'), 100) selnodeState = tempnode.getState() tempnode.setBin('inactive', 0, 1) initialState = tempnode.getState() # Set up a 1-by-1 buffer to which we'll just render the pixel under # the mouse. selectBuffer = mainWin.makeTextureBuffer('selectBuffer', 1, 1) selectBuffer.setClearColor(Vec4(0, 0, 0, 1)) self.selectBuffer = selectBuffer selectLens = PerspectiveLens() selectLens.setNearFar(mainLens.getNear(), mainLens.getFar()) selectLens.setFocalLength(mainLens.getFocalLength()) selectCamera = base.makeCamera(selectBuffer, lens=selectLens) selectCamera.node().setScene(scene) selectCamera.node().setInitialState(initialState) selectCamera.node().setTagState('sel', selnodeState) selectCamera.node().setTagStateKey('sel') selectCamera.node().setCameraMask(BitMask32(16)) self.selectLens = selectLens self.selectTex = selectBuffer.getTexture() self.selectTex.makeRamImage() self.gsg = mainWin.getGsg() # Set up a texture card to render the silhouette texture with the # Sobel shader, which will draw the edges of the silhouettes. silhouetteCard = silhouetteBuffer.getTextureCard() silhouetteCard.setTransparency(1) inkGen = loader.loadShader('sobel.sha') silhouetteCard.setShader(inkGen) silhouetteCard.setShaderInput('separation', 0.001, 0) silhouetteCard.reparentTo(render2d) self.silhouetteCard = silhouetteCard self.accept(mainWin.getWindowEvent(), self.windowEventHandler) self.accept('mouse1', self.mouseDownHandler, ['l']) self.accept('mouse1-up', self.mouseUpHandler, ['l']) self.accept('mouse3', self.mouseDownHandler, ['r']) self.accept('mouse3-up', self.mouseUpHandler, ['r']) self.buttonWatcher = ButtonWatcher([ KeyboardButton.shift(), KeyboardButton.control(), MouseButton.one(), MouseButton.three(), ]) CameraController.getInstance().addEventHandler(EVT_CAMERA_MODE, self._cameraModeHandler) self.enable(False)
def __init__(self, charId, charNr, controls): FSM.__init__(self, "FSM-Player{}".format(charNr)) self.charId = charId charPath = "characters/character{}/".format(charNr) self.character = Actor( charPath + "char", { "Idle": charPath + "idle", "Walk": charPath + "walk", "Walk_back": charPath + "walk_back", "Punch_l": charPath + "punch_l", "Punch_r": charPath + "punch_r", "Kick_l": charPath + "kick_l", "Kick_r": charPath + "kick_r", "Defend": charPath + "defend", "Hit": charPath + "hit", "Defeated": charPath + "defeated", }, ) self.character.reparentTo(render) self.character.hide() self.walkSpeed = 2.0 # units per second if controls == "p1": self.character.setH(90) self.leftButton = KeyboardButton.asciiKey("d") self.rightButton = KeyboardButton.asciiKey("f") self.punchLButton = KeyboardButton.asciiKey("q") self.punchRButton = KeyboardButton.asciiKey("w") self.kickLButton = KeyboardButton.asciiKey("a") self.kickRButton = KeyboardButton.asciiKey("s") self.defendButton = KeyboardButton.asciiKey("e") elif controls == "p2": self.character.setH(-90) self.leftButton = KeyboardButton.right() self.rightButton = KeyboardButton.left() self.punchLButton = KeyboardButton.asciiKey("i") self.punchRButton = KeyboardButton.asciiKey("o") self.kickLButton = KeyboardButton.asciiKey("k") self.kickRButton = KeyboardButton.asciiKey("l") self.defendButton = KeyboardButton.asciiKey("p") self.getPos = self.character.getPos self.getX = self.character.getX characterSphere = CollisionSphere(0, 0, 1.0, 0.5) self.collisionNodeName = "character{}Collision".format(charId) characterColNode = CollisionNode(self.collisionNodeName) characterColNode.addSolid(characterSphere) self.characterCollision = self.character.attachNewNode(characterColNode) # Uncomment this line to show collision solids # self.characterCollision.show() base.pusher.addCollider(self.characterCollision, self.character) base.cTrav.addCollider(self.characterCollision, base.pusher) characterHitRay = CollisionSegment(0, -0.5, 1.0, 0, -0.8, 1.0) characterColNode.addSolid(characterHitRay) self.audioStep = base.audio3d.loadSfx("assets/audio/step.ogg") self.audioStep.setLoop(True) base.audio3d.attachSoundToObject(self.audioStep, self.character) self.audioHit = base.audio3d.loadSfx("assets/audio/hit.ogg") self.audioHit.setLoop(False) base.audio3d.attachSoundToObject(self.audioStep, self.character)
def movePlayer(self, player, dt): mw = self.base.mouseWatcherNode heading = self.headingTurner.getHeading() # Heading is the roll value for this model lookAngle = player.getP() # y is forward/back, x is left/right, z is up/down curVel = self.getVelocity(player) # Accelerate in the direction the player is currently facing y = 0 if self.keys["front"]: y = 1 elif self.keys["back"]: y = -1 x = 0 if self.keys["strafeLeft"]: x = -1 elif self.keys["strafeRight"]: x = 1 z = 0 if self.keys["up"]: z = 1 elif self.keys["down"]: z = -1 if mw.isButtonDown(KeyboardButton.shift()): x *= 2 y *= 2 if self.keys["jump"]: if not self.jumping: self.jumpTime = 0 self.jumping = True self.jumpZ = 0 now = globalClock.getFrameTime() if x or y: if not self.walkCycle: self.walkCycle = now heading_rad = DEG_TO_RAD * (360 - heading) newFwdBack = Vec3(sin(heading_rad)*y, cos(heading_rad) * y, 0) if self.flyMode: newFwdBack.z = sin(DEG_TO_RAD * lookAngle) * y newStrafe = Vec3(-sin(heading_rad-pi/2) * x, -cos(heading_rad-pi/2)*x, 0) newUpDown = Vec3(0, 0, z) newVel = (newFwdBack + newStrafe + newUpDown) * ACCELERATION playerVel = (curVel * (STEPS-1) + newVel) / STEPS self.setVelocity(player, playerVel) if self.mouseLook and mw.hasMouse(): x, y = mw.getMouseX(), mw.getMouseY() dx, dy = x, y self.headingTurner.setTurnRate(math.sin(dx) * -1440) #self.headingTurner.setTarget(dx / pi) self.lookTurner.setTurnRate(math.sin(dy) * 1440) #self.lookTurner.setTarget(y * 90) self.lastMouseX, self.lastMouseY = x, y if self.mouseGrabbed: self.base.win.movePointer(0, int(self.base.win.getProperties().getXSize() / 2), int(self.base.win.getProperties().getYSize() / 2)) # Change heading if left or right is being pressed now = globalClock.getFrameTime() if self.keys["turnRight"]: self.headingTurner.updateTurn(-1, dt) elif self.keys["turnLeft"]: self.headingTurner.updateTurn(1, dt) elif self.keys["reverse"]: self.headingTurner.setTarget(heading + 180) elif not self.mouseLook: self.headingTurner.unTurn(dt) heading = self.headingTurner.update(dt) # Adjust view angle if self.keys["lookDown"]: self.lookTurner.updateTurn(-1, dt) self.lookSticky = True elif self.keys["lookUp"]: self.lookTurner.updateTurn(1, dt) self.lookSticky = True elif self.keys["lookReset"]: self.lookTurner.setTarget(0) self.lookSticky = False elif not self.mouseLook: self.lookTurner.unTurn(dt) if self.lookTurner.getTurnRate() == 0: if (x or y or self.jumpZ) and not self.mouseLook: self.lookSticky = False if not self.lookSticky: self.lookTurner.setTarget(0) lookAngle = self.lookTurner.update(dt) player.setH(heading) player.setP(lookAngle) # Finally, update the position as with any other object self.updatePos(player, now, dt)