def update(self, task=None): """ Updates position of sounds in the 3D audio system. Will be called automatically in a task. """ # Update the positions of all sounds based on the objects # to which they are attached # The audio manager is not active so do nothing if hasattr(self.audio_manager, "getActive"): if self.audio_manager.getActive()==0: return Task.cont for known_object in self.sound_dict.keys(): tracked_sound = 0 while tracked_sound < len(self.sound_dict[known_object]): sound = self.sound_dict[known_object][tracked_sound] pos = known_object.getPos(self.root) vel = self.getSoundVelocity(sound) sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) tracked_sound += 1 # Update the position of the listener based on the object # to which it is attached if self.listener_target: pos = self.listener_target.getPos(self.root) forward = self.root.getRelativeVector(self.listener_target, Vec3.forward()) up = self.root.getRelativeVector(self.listener_target, Vec3.up()) vel = self.getListenerVelocity() self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2]) else: self.audio_manager.audio3dSetListenerAttributes(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1) return Task.cont
def matchPose(self, pose_rig): for node, parent in pose_rig.exposed_joints: if node.getName() not in joints_config: continue joint_config = joints_config[node.getName()] if 'joints' not in joint_config: continue joints = joint_config['joints'] if len(joints) == 0: continue box_np = self.root.find(node.getName()) if len(joints) > 1: pos = node.getPos(pose_rig.actor) hpr = node.getHpr(pose_rig.actor) box_np.setPosHpr(self.root, pos, hpr) else: joint = joints.keys()[0] child_node, child_parent = next((child_node, child_parent) for child_node, child_parent in pose_rig.exposed_joints if child_node.getName() == joint) box_np.setPos(child_parent, child_node.getPos(child_parent) / 2.0) quat = Quat() lookAt(quat, child_node.getPos(child_parent), Vec3.up()) box_np.setQuat(child_parent, quat) box_np.node().clearForces()
def __init__(self, cr): DistributedEntity.__init__(self, cr) self.height = 1.0 self.raiseSpeed = 1 self.stompSpeed = 1 self.scale = Vec3(1) self.moveDir = Vec3.up()
def step(self, task): distance = ClockObject.getGlobalClock().getDt() * self.speed rotMat = Mat3.rotateMatNormaxis(self.avatar.getH(), Vec3.up()) step = Vec3(rotMat.xform(Vec3.forward() * distance)) self.avatar.setFluidPos(Point3(self.avatar.getPos() + step)) return Task.cont
def __init__(self, cr): DistributedEntity.__init__(self, cr) FSM.__init__(self, 'func_rotating') self.state = 0 self.axis = Vec3.up() self.timeToFull = 5.0 self.speed = 50.0 self.spinTrack = None
def create_colliders(root, pose_rig, joints_config): for node, parent in pose_rig.exposed_joints: if node.getName() not in joints_config: continue joint_config = joints_config[node.getName()] if "joints" not in joint_config: continue joints = joint_config["joints"] if len(joints) == 0: continue mass = joint_config["mass"] if "mass" in joint_config else 1 box_rb = BulletRigidBodyNode(node.getName()) box_rb.setMass(1.0) # box_rb.setLinearDamping(0.2) # box_rb.setAngularDamping(0.9) # box_rb.setFriction(1.0) # box_rb.setAnisotropicFriction(1.0) # box_rb.setRestitution(0.0) for joint in joints: child_node, child_parent = next( (child_node, child_parent) for child_node, child_parent in pose_rig.exposed_joints if child_node.getName() == joint ) pos = child_node.getPos(child_parent) width = pos.length() / 2.0 scale = Vec3(3, width, 3) shape = BulletBoxShape(scale) quat = Quat() lookAt(quat, child_node.getPos(child_parent), Vec3.up()) if len(joints) > 1: transform = TransformState.makePosHpr(child_node.getPos(child_parent) / 2.0, quat.getHpr()) else: transform = TransformState.makeHpr(quat.getHpr()) box_rb.addShape(shape, transform) box_np = root.attachNewNode(box_rb) if len(joints) > 1: pos = node.getPos(pose_rig.actor) hpr = node.getHpr(pose_rig.actor) box_np.setPosHpr(root, pos, hpr) else: box_np.setPos(child_parent, child_node.getPos(child_parent) / 2.0) box_np.lookAt(child_parent, child_node.getPos(child_parent)) yield box_np
def get_normal(self): seen = set() points = [p for p in self.points if p not in seen and not seen.add(p)] if len(points) >= 3: v1 = points[0] - points[1] v2 = points[1] - points[2] normal = v1.cross(v2) normal.normalize() else: normal = Vec3.up() return normal
def guide_missile(self, task): try: quat = Quat() lookAt(quat, self.target.np.getPos() - self.missile.anp.getPos(), Vec3.up()) self.missile.anp.setQuat(quat) fwd = quat.getForward() fwd.normalize() mvel = self.missile.anpo.getVelocity().length() self.missile.anpo.setVelocity(fwd*mvel) except: return task.done return task.cont
def __processSwimming(self): procSwimCollector.start() if self.__footContact: absSlopeDot = round(self.__footContact[2].dot(Vec3.up()), 2) if self.__targetPos.z - 0.1 < self.__footContact[0].z and (self.__linearVelocity.z < 0.0 or absSlopeDot < 1): self.__targetPos.z = self.__footContact[0].z self.__linearVelocity.z = 0.0 if self.__headContact and self.__capsuleTop >= self.__headContact[0].z and self.__linearVelocity.z > 0.0: self.__linearVelocity.z = 0.0 procSwimCollector.stop()
def __applyLinearVelocity(self): globalVel = self.__linearVelocity * self.__timeStep if self.predictFutureSpace and not self.__checkFutureSpace(globalVel): return if self.__footContact is not None and self.minSlopeDot and self.movementState != "swimming": normalVel = Vec3(globalVel) normalVel.normalize() floorNormal = self.__footContact[2] #worldToAvatar = self.movementParent.getTransform(render).getInverse().getMat() #contactNormalAv = worldToAvatar * floorNormal #velAv = worldToAvatar * globalVel #forward = contactNormalAv.cross(Vec3.right()) #forward.normalize() #globalVel = forward * self.__linearVelocity.length() * self.__timeStep absSlopeDot = round(floorNormal.dot(Vec3.up()), 2) def applyGravity(): self.__targetPos -= Vec3( floorNormal.x, floorNormal.y, 0.0) * self.gravity * self.__timeStep * 0.1 if absSlopeDot <= self.minSlopeDot: applyGravity() if globalVel != Vec3(): globalVelDir = Vec3(globalVel) globalVelDir.normalize() fn = Vec3(floorNormal.x, floorNormal.y, 0.0) fn.normalize() velDot = 1.0 - globalVelDir.angleDeg(fn) / 180.0 if velDot < 0.5: self.__targetPos -= Vec3(fn.x * globalVel.x, fn.y * globalVel.y, 0.0) * velDot globalVel *= velDot elif self.__slopeAffectsSpeed and globalVel != Vec3(): applyGravity() elif self.movementState == "swimming" and not self.isOnGround(): self.__targetPos -= Vec3(0, 0, -self.gravity * self.__timeStep * 0.1) self.__targetPos += globalVel
def __init__(self, air, dispatch): DistributedEntityAI.__init__(self, air, dispatch) self.height = 1.0 self.stompSpeed = 1 self.raiseSpeed = 1 self.timeOnGround = 0.0 self.timeInAir = 0.0 self.damage = 20 self.scale = Vec3(1) self.floorColl = None self.damaged = [] self.moveDir = Vec3.up() self.stomped = False self.startDelay = 0.0
def update(self, task=None): """ Updates position of sounds in the 3D audio system. Will be called automatically in a task. """ # Update the positions of all sounds based on the objects # to which they are attached # The audio manager is not active so do nothing if hasattr(self.audio_manager, "getActive"): if self.audio_manager.getActive() == 0: return Task.cont for known_object, sounds in list(self.sound_dict.items()): node_path = known_object.getNodePath() if not node_path: # The node has been deleted. del self.sound_dict[known_object] continue pos = node_path.getPos(self.root) for sound in sounds: vel = self.getSoundVelocity(sound) sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) # Update the position of the listener based on the object # to which it is attached if self.listener_target: pos = self.listener_target.getPos(self.root) forward = self.root.getRelativeVector(self.listener_target, Vec3.forward()) up = self.root.getRelativeVector(self.listener_target, Vec3.up()) vel = self.getListenerVelocity() self.audio_manager.audio3dSetListenerAttributes( pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2]) else: self.audio_manager.audio3dSetListenerAttributes( 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1) return Task.cont
def __apply_linear_velocity(self): global_vel = self.node.getQuat(render).xform( self.__linear_velocity) * self.__time_step if self.predict_future_space and not self.__check_future_space( global_vel): return if self.__foot_contact is not None and self.min_slope_dot and self.movement_state != "flying": normal_vel = Vec3(global_vel) normal_vel.normalize() floor_normal = self.__foot_contact[2] abs_slope_dot = round(floor_normal.dot(Vec3.up()), 2) def apply_gravity(): self.__current_pos -= Vec3( floor_normal.x, floor_normal.y, 0.0) * self.gravity * self.__time_step * 0.1 if abs_slope_dot <= self.min_slope_dot: apply_gravity() if global_vel != Vec3(): global_vel_dir = Vec3(global_vel) global_vel_dir.normalize() fn = Vec3(floor_normal.x, floor_normal.y, 0.0) fn.normalize() vel_dot = 1.0 - global_vel_dir.angleDeg(fn) / 180.0 if vel_dot < 0.5: self.__current_pos -= Vec3(fn.x * global_vel.x, fn.y * global_vel.y, 0.0) * vel_dot global_vel *= vel_dot elif self.__slope_affects_speed and global_vel != Vec3(): apply_gravity() self.__current_pos += global_vel
def __applyLinearVelocity(self): globalVel = self.movementParent.getQuat(render).xform( self.__linearVelocity) * self.__timeStep if self.predictFutureSpace and not self.__checkFutureSpace(globalVel): return if self.__footContact is not None and self.minSlopeDot and self.movementState != "flying": normalVel = Vec3(globalVel) normalVel.normalize() floorNormal = self.__footContact[2] absSlopeDot = round(floorNormal.dot(Vec3.up()), 2) def applyGravity(): self.__currentPos -= Vec3( floorNormal.x, floorNormal.y, 0.0) * self.gravity * self.__timeStep * 0.1 if absSlopeDot <= self.minSlopeDot: applyGravity() if globalVel != Vec3(): globalVelDir = Vec3(globalVel) globalVelDir.normalize() fn = Vec3(floorNormal.x, floorNormal.y, 0.0) fn.normalize() velDot = 1.0 - globalVelDir.angleDeg(fn) / 180.0 if velDot < 0.5: self.__currentPos -= Vec3(fn.x * globalVel.x, fn.y * globalVel.y, 0.0) * velDot globalVel *= velDot elif self.__slopeAffectsSpeed and globalVel != Vec3(): applyGravity() self.__currentPos += globalVel
def update(self, task=None): """ Updates position of sounds in the 3D audio system. Will be called automatically in a task. """ # Update the positions of all sounds based on the objects # to which they are attached # The audio manager is not active so do nothing if hasattr(self.audio_manager, "getActive"): if self.audio_manager.getActive() == 0: return Task.cont for known_object in self.sound_dict.keys(): tracked_sound = 0 while tracked_sound < len(self.sound_dict[known_object]): sound = self.sound_dict[known_object][tracked_sound] pos = known_object.getPos(self.root) vel = self.getSoundVelocity(sound) sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) tracked_sound += 1 # Update the position of the listener based on the object # to which it is attached if self.listener_target: pos = self.listener_target.getPos(self.root) forward = self.root.getRelativeVector(self.listener_target, Vec3.forward()) up = self.root.getRelativeVector(self.listener_target, Vec3.up()) vel = self.getListenerVelocity() self.audio_manager.audio3dSetListenerAttributes( pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2]) else: self.audio_manager.audio3dSetListenerAttributes( 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1) return Task.cont
def update(self, task=None): """ Updates position of sounds in the 3D audio system. Will be called automatically in a task. """ # Update the positions of all sounds based on the objects # to which they are attached # The audio manager is not active so do nothing if hasattr(self.audio_manager, "getActive"): if self.audio_manager.getActive()==0: return Task.cont for known_object, sounds in list(self.sound_dict.items()): node_path = known_object.getNodePath() if not node_path: # The node has been deleted. del self.sound_dict[known_object] continue pos = node_path.getPos(self.root) for sound in sounds: vel = self.getSoundVelocity(sound) sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) # Update the position of the listener based on the object # to which it is attached if self.listener_target: pos = self.listener_target.getPos(self.root) forward = self.root.getRelativeVector(self.listener_target, Vec3.forward()) up = self.root.getRelativeVector(self.listener_target, Vec3.up()) vel = self.getListenerVelocity() self.audio_manager.audio3dSetListenerAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], forward[0], forward[1], forward[2], up[0], up[1], up[2]) else: self.audio_manager.audio3dSetListenerAttributes(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1) return Task.cont
def primitives(self, vdata): vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') w = ROAD_WIDTH / 2.0 v = 0 for a, b in self.edges: a, b = self.points[a], self.points[b] ab = b - a n = ab.length() inc = abs(a.z - b.z) / n probes = max(2, n / 25) ab_ = Vec3(ab) ab_.normalize() pab = Vec3.up().cross(ab_) * w road = GeomTristrips(Geom.UHStatic) for i in range(0, int(probes) + 1): p = a + ab / probes * i p1 = p + pab p2 = p - pab z = max(elevation(p1.x, p1.y), elevation(p2.x, p2.y)) p1.z = z + 0.2 p2.z = z + 0.2 vertex.addData3f(p1) vertex.addData3f(p2) if inc > 0.1: color.addData4f(0.4, 0.0, 0.0, 0.0) color.addData4f(0.4, 0.0, 0.0, 0.0) elif n > 1000: color.addData4f(0.0, 0.0, 0.4, 0.0) color.addData4f(0.0, 0.0, 0.4, 0.0) else: color.addData4f(0.2, 0.2, 0.2, 0.0) color.addData4f(0.2, 0.2, 0.2, 0.0) road.addVertices(v, v + 1) v += 2 road.closePrimitive() yield road
def __applyLinearVelocity(self): globalVel = self.movementParent.getQuat(render).xform(self.__linearVelocity) * self.__timeStep if self.predictFutureSpace and not self.__checkFutureSpace(globalVel): return if self.__footContact is not None and self.minSlopeDot and self.movementState != "flying": normalVel = Vec3(globalVel) normalVel.normalize() floorNormal = self.__footContact[2] absSlopeDot = round(floorNormal.dot(Vec3.up()), 2) def applyGravity(): self.__currentPos -= Vec3(floorNormal.x, floorNormal.y, 0.0) * self.gravity * self.__timeStep * 0.1 if absSlopeDot <= self.minSlopeDot: applyGravity() if globalVel != Vec3(): globalVelDir = Vec3(globalVel) globalVelDir.normalize() fn = Vec3(floorNormal.x, floorNormal.y, 0.0) fn.normalize() velDot = 1.0 - globalVelDir.angleDeg(fn) / 180.0 if velDot < 0.5: self.__currentPos -= Vec3(fn.x * globalVel.x, fn.y * globalVel.y, 0.0) * velDot globalVel *= velDot elif self.__slopeAffectsSpeed and globalVel != Vec3(): applyGravity() self.__currentPos += globalVel
def __updateTask(self, task): # TODO -- This function does a lot of math, I measured it to take .5 ms on my laptop # That's a lot of time for something miniscule like sway and bob. dt = globalClock.getDt() time = globalClock.getFrameTime() if base.localAvatar.isFirstPerson(): eyePoint = base.localAvatar.getEyePoint() if base.localAvatar.walkControls.crouching: eyePoint[2] = eyePoint[2] / 2.0 eyePoint[2] = CIGlobals.lerpWithRatio(eyePoint[2], self.lastEyeHeight, 0.4) self.lastEyeHeight = eyePoint[2] camRootAngles = Vec3(0) # Mouse look around mw = base.mouseWatcherNode if mw.hasMouse(): md = base.win.getPointer(0) center = Point2(base.win.getXSize() / 2, base.win.getYSize() / 2) xDist = md.getX() - center.getX() yDist = md.getY() - center.getY() sens = self.__getMouseSensitivity() angular = -(xDist * sens) / dt base.localAvatar.walkControls.controller.setAngularMovement( angular) camRootAngles.setY(self.lastPitch - yDist * sens) if camRootAngles.getY() > FPSCamera.MaxP: camRootAngles.setY(FPSCamera.MaxP) yDist = 0 elif camRootAngles.getY() < FPSCamera.MinP: yDist = 0 camRootAngles.setY(FPSCamera.MinP) base.win.movePointer(0, int(center.getX()), int(center.getY())) if base.localAvatar.isFirstPerson(): # Camera / viewmodel bobbing vmBob = Point3(0) vmAngles = Vec3(0) vmRaise = Point3(0) camBob = Point3(0) maxSpeed = base.localAvatar.walkControls.BattleRunSpeed * 16.0 speed = base.localAvatar.walkControls.speeds.length() * 16.0 speed = max(-maxSpeed, min(maxSpeed, speed)) bobOffset = CIGlobals.remapVal(speed, 0, maxSpeed, 0.0, 1.0) self.bobTime += (time - self.lastBobTime) * bobOffset self.lastBobTime = time # Calculate the vertical bob cycle = self.bobTime - int( self.bobTime / self.BobCycleMax) * self.BobCycleMax cycle /= self.BobCycleMax if cycle < self.BobUp: cycle = math.pi * cycle / self.BobUp else: cycle = math.pi + math.pi * (cycle - self.BobUp) / (1.0 - self.BobUp) verticalBob = speed * 0.005 verticalBob = verticalBob * 0.3 + verticalBob * 0.7 * math.sin( cycle) verticalBob = max(-7.0, min(4.0, verticalBob)) verticalBob /= 16.0 # Calculate the lateral bob cycle = self.bobTime - int( self.bobTime / self.BobCycleMax * 2) * self.BobCycleMax * 2 cycle /= self.BobCycleMax * 2 if cycle < self.BobUp: cycle = math.pi * cycle / self.BobUp else: cycle = math.pi + math.pi * (cycle - self.BobUp) / (1.0 - self.BobUp) lateralBob = speed * 0.005 lateralBob = lateralBob * 0.3 + lateralBob * 0.7 * math.sin(cycle) lateralBob = max(-7.0, min(4.0, lateralBob)) lateralBob /= 16.0 # Apply bob, but scaled down a bit vmBob.set(lateralBob * 0.8, 0, verticalBob * 0.1) # Z bob a bit more vmBob[2] += verticalBob * 0.1 # Bob the angles vmAngles[2] += verticalBob * 0.5 vmAngles[1] -= verticalBob * 0.4 vmAngles[0] -= lateralBob * 0.3 # ================================================================ # Viewmodel lag/sway angles = self.camRoot.getHpr(render) quat = Quat() quat.setHpr(angles) invQuat = Quat() invQuat.invertFrom(quat) maxVMLag = 1.5 lagforward = quat.getForward() if dt != 0.0: lagdifference = lagforward - self.lastFacing lagspeed = 5.0 lagdiff = lagdifference.length() if (lagdiff > maxVMLag) and (maxVMLag > 0.0): lagscale = lagdiff / maxVMLag lagspeed *= lagscale self.lastFacing = CIGlobals.extrude(self.lastFacing, lagspeed * dt, lagdifference) self.lastFacing.normalize() lfLocal = invQuat.xform(lagdifference) vmBob = CIGlobals.extrude(vmBob, 5.0 / 16.0, lfLocal * -1.0) pitch = angles[1] if pitch > 180: pitch -= 360 elif pitch < -180: pitch += 360 vmBob = CIGlobals.extrude(vmBob, pitch * (0.035 / 16), Vec3.forward()) vmBob = CIGlobals.extrude(vmBob, pitch * (0.03 / 16), Vec3.right()) vmBob = CIGlobals.extrude(vmBob, pitch * (0.02 / 16), Vec3.up()) # ================================================================ vmRaise.set( 0, 0, 0 ) #(0, abs(camRootAngles.getY()) * -0.002, camRootAngles.getY() * 0.002) camBob.set(0, 0, 0) # Apply bob, raise, and sway to the viewmodel. self.viewModel.setPos(vmBob + vmRaise + self.lastVMPos) self.vmRoot2.setHpr(vmAngles) self.camRoot.setPos(eyePoint + camBob) newPitch = camRootAngles.getY() if abs(newPitch - self.lastPitch) > self.PitchUpdateEpsilon: # Broadcast where our head is looking head = base.localAvatar.getPart("head") if head and not head.isEmpty(): # Constrain the head pitch a little bit so it doesn't look like their head snapped headPitch = max(-47, newPitch) headPitch = min(75, headPitch) base.localAvatar.b_setLookPitch(headPitch) self.lastPitch = newPitch if base.localAvatar.isFirstPerson(): # Apply punch angle self.decayPunchAngle() camRootAngles += self.punchAngle self.camRoot.setHpr(camRootAngles) return task.cont
def handleAvatarControls(self, task): """ Check on the arrow keys and update the avatar. """ # get the button states: run = inputState.isSet("run") forward = inputState.isSet("forward") reverse = inputState.isSet("reverse") turnLeft = inputState.isSet("turnLeft") turnRight = inputState.isSet("turnRight") slideLeft = inputState.isSet("slideLeft") slideRight = inputState.isSet("slideRight") jump = inputState.isSet("jump") avatarControlForwardSpeed = 0 avatarControlReverseSpeed = 0 avatarControlSLeftSpeed = 0 avatarControlSRightSpeed = 0 if forward: if not self.hasSetForwardInitTime: self.forwardInitTime = globalClock.getFrameTime() self.hasSetForwardInitTime = True self.isAtZeroForward = False self.hasSetForwardStopTime = False timeSinceForwardSet = globalClock.getFrameTime() - self.forwardInitTime if timeSinceForwardSet == 0: avatarControlForwardSpeed = 0.0 else: avatarControlForwardSpeed = min((timeSinceForwardSet / self.avatarControlForwardSpeed) * 750, self.avatarControlForwardSpeed) else: if self.hasSetForwardInitTime: self.hasSetForwardInitTime = False if not self.hasSetForwardStopTime: self.forwardStopTime = globalClock.getFrameTime() self.hasSetForwardStopTime = True timeSinceForwardStop = globalClock.getFrameTime() - self.forwardStopTime if timeSinceForwardStop == 0: avatarControlForwardSpeed = 16.0 elif not self.isAtZeroForward: avatarControlForwardSpeed = self.avatarControlForwardSpeed - (timeSinceForwardStop * 50) if avatarControlForwardSpeed <= 0.5: avatarControlForwardSpeed = 0.0 self.isAtZeroForward = True self.hasSetForwardStopTime = False if reverse: if not self.hasSetReverseInitTime: self.reverseInitTime = globalClock.getFrameTime() self.hasSetReverseInitTime = True self.isAtZeroReverse = False self.hasSetReverseStopTime = False timeSinceReverseSet = globalClock.getFrameTime() - self.reverseInitTime if timeSinceReverseSet == 0: avatarControlReverseSpeed = 0.0 else: avatarControlReverseSpeed = min((timeSinceReverseSet / self.avatarControlReverseSpeed) * 400, self.avatarControlReverseSpeed) else: if self.hasSetReverseInitTime: self.hasSetReverseInitTime = False if not self.hasSetReverseStopTime: self.reverseStopTime = globalClock.getFrameTime() self.hasSetReverseStopTime = True timeSinceReverseStop = globalClock.getFrameTime() - self.reverseStopTime if timeSinceReverseStop == 0: avatarControlReverseSpeed = 16.0 elif not self.isAtZeroReverse: avatarControlReverseSpeed = self.avatarControlReverseSpeed - (timeSinceReverseStop * 20) if avatarControlReverseSpeed <= 0.5: avatarControlReverseSpeed = 0.0 self.isAtZeroReverse = True self.hasSetReverseStopTime = False if slideLeft: if not self.hasSetSLeftInitTime: self.sLeftInitTime = globalClock.getFrameTime() self.hasSetSLeftInitTime = True self.isAtZeroSLeft = False self.hasSetSLeftStopTime = False timeSinceSLeftSet = globalClock.getFrameTime() - self.sLeftInitTime if timeSinceSLeftSet == 0: avatarControlSLeftSpeed = 0.0 else: avatarControlSLeftSpeed = min((timeSinceSLeftSet / self.avatarControlForwardSpeed) * 750, self.avatarControlForwardSpeed) else: if self.hasSetSLeftInitTime: self.hasSetSLeftInitTime = False if not self.hasSetSLeftStopTime: self.sLeftStopTime = globalClock.getFrameTime() self.hasSetSLeftStopTime = True timeSinceSLeftStop = globalClock.getFrameTime() - self.sLeftStopTime if timeSinceSLeftStop == 0: avatarControlSLeftSpeed = 16.0 elif not self.isAtZeroSLeft: avatarControlSLeftSpeed = self.avatarControlForwardSpeed - (timeSinceSLeftStop * 50) if avatarControlSLeftSpeed <= 0.5: avatarControlSLeftSpeed = 0.0 self.isAtZeroSLeft = True self.hasSetSLeftStopTime = False if slideRight: if not self.hasSetSRightInitTime: self.sRightInitTime = globalClock.getFrameTime() self.hasSetSRightInitTime = True self.isAtZeroSRight = False self.hasSetSRightStopTime = False timeSinceSRightSet = globalClock.getFrameTime() - self.sRightInitTime if timeSinceSRightSet == 0: avatarControlSRightSpeed = 0.0 else: avatarControlSRightSpeed = min((timeSinceSRightSet / self.avatarControlForwardSpeed) * 750, self.avatarControlForwardSpeed) else: if self.hasSetSRightInitTime: self.hasSetSRightInitTime = False if not self.hasSetSRightStopTime: self.sRightStopTime = globalClock.getFrameTime() self.hasSetSRightStopTime = True timeSinceSRightStop = globalClock.getFrameTime() - self.sRightStopTime if timeSinceSRightStop == 0: avatarControlSRightSpeed = 16.0 elif not self.isAtZeroSRight: avatarControlSRightSpeed = self.avatarControlForwardSpeed - (timeSinceSRightStop * 50) if avatarControlSRightSpeed <= 0.5: avatarControlSRightSpeed = 0.0 self.isAtZeroSRight = True self.hasSetSRightStopTime = False # Check for Auto-Run #if 'localAvatar' in __builtins__: # if base.localAvatar and base.localAvatar.getAutoRun(): # forward = 1 # reverse = 0 # Determine what the speeds are based on the buttons: self.speed=(avatarControlForwardSpeed or -avatarControlReverseSpeed) # Slide speed is a scaled down version of forward speed # Note: you can multiply a factor in here if you want slide to # be slower than normal walk/run. Let's try full speed. #self.slideSpeed=(slideLeft and -self.avatarControlForwardSpeed*0.75 or # slideRight and self.avatarControlForwardSpeed*0.75) self.slideSpeed=(-avatarControlSLeftSpeed or avatarControlSRightSpeed) self.rotationSpeed=not (slideLeft or slideRight) and ( (turnLeft and self.avatarControlRotateSpeed) or (turnRight and -self.avatarControlRotateSpeed)) if self.speed and self.slideSpeed: self.speed *= GravityWalker.DiagonalFactor self.slideSpeed *= GravityWalker.DiagonalFactor debugRunning = inputState.isSet("debugRunning") if(debugRunning): self.speed*=base.debugRunningMultiplier self.slideSpeed*=base.debugRunningMultiplier self.rotationSpeed*=1.25 if self.needToDeltaPos: self.setPriorParentVector() self.needToDeltaPos = 0 if self.wantDebugIndicator: self.displayDebugInfo() if self.lifter.isOnGround(): if self.isAirborne: self.isAirborne = 0 assert self.debugPrint("isAirborne 0 due to isOnGround() true") impact = self.lifter.getImpactVelocity() if impact < -30.0: messenger.send("jumpHardLand") self.startJumpDelay(0.3) else: messenger.send("jumpLand") if impact < -5.0: self.startJumpDelay(0.2) # else, ignore the little potholes. assert self.isAirborne == 0 self.priorParent = Vec3.zero() if jump and self.mayJump: # The jump button is down and we're close # enough to the ground to jump. self.lifter.addVelocity(self.avatarControlJumpForce) messenger.send("jumpStart") self.isAirborne = 1 assert self.debugPrint("isAirborne 1 due to jump") else: if self.isAirborne == 0: assert self.debugPrint("isAirborne 1 due to isOnGround() false") self.isAirborne = 1 self.__oldPosDelta = self.avatarNodePath.getPosDelta(render) # How far did we move based on the amount of time elapsed? self.__oldDt = ClockObject.getGlobalClock().getDt() dt=self.__oldDt # Check to see if we're moving at all: self.moving = self.speed or self.slideSpeed or self.rotationSpeed or (self.priorParent!=Vec3.zero()) if self.moving: distance = dt * self.speed slideDistance = dt * self.slideSpeed rotation = dt * self.rotationSpeed # Take a step in the direction of our previous heading. if distance or slideDistance or self.priorParent != Vec3.zero(): # rotMat is the rotation matrix corresponding to # our previous heading. rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up()) if self.isAirborne: forward = Vec3.forward() else: contact = self.lifter.getContactNormal() forward = contact.cross(Vec3.right()) # Consider commenting out this normalize. If you do so # then going up and down slops is a touch slower and # steeper terrain can cut the movement in half. Without # the normalize the movement is slowed by the cosine of # the slope (i.e. it is multiplied by the sign as a # side effect of the cross product above). forward.normalize() self.vel=Vec3(forward * distance) if slideDistance: if self.isAirborne: right = Vec3.right() else: right = forward.cross(contact) # See note above for forward.normalize() right.normalize() self.vel=Vec3(self.vel + (right * slideDistance)) self.vel=Vec3(rotMat.xform(self.vel)) step=self.vel + (self.priorParent * dt) self.avatarNodePath.setFluidPos(Point3( self.avatarNodePath.getPos()+step)) self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation) else: self.vel.set(0.0, 0.0, 0.0) if self.moving or jump: messenger.send("avatarMoving") return Task.cont
def enterNormal(self): self.notify.debug('enterNormal') self.setAnimState('Catching', 1.0) if self.isLocal: self.activity.orthoWalk.start() self.toon.lerpLookAt(Vec3.forward() + Vec3.up(), time=0.2, blink=0)
def moveUp(self): vp = base.viewportMgr.activeViewport if not vp or not vp.is2D(): return self.updatePos(self.pos + self.getMoveDelta(Vec3.up(), vp))