NonPhysicsWalker.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. """
  2. NonPhysicsWalker.py is for avatars.
  3. A walker control such as this one provides:
  4. - creation of the collision nodes
  5. - handling the keyboard and mouse input for avatar movement
  6. - moving the avatar
  7. it does not:
  8. - play sounds
  9. - play animations
  10. although it does send messeges that allow a listener to play sounds or
  11. animations based on walker events.
  12. """
  13. from direct.directnotify import DirectNotifyGlobal
  14. from direct.showbase import DirectObject
  15. from direct.controls.ControlManager import CollisionHandlerRayStart
  16. from direct.showbase.InputStateGlobal import inputState
  17. from direct.task.Task import Task
  18. from pandac.PandaModules import *
  19. class NonPhysicsWalker(DirectObject.DirectObject):
  20. notify = DirectNotifyGlobal.directNotify.newCategory("NonPhysicsWalker")
  21. wantDebugIndicator = base.config.GetBool('want-avatar-physics-indicator', 0)
  22. # Ghost mode overrides this:
  23. slideName = "slide-is-disabled"
  24. # special methods
  25. def __init__(self):
  26. DirectObject.DirectObject.__init__(self)
  27. self.worldVelocity = Vec3.zero()
  28. self.collisionsActive = 0
  29. self.speed=0.0
  30. self.rotationSpeed=0.0
  31. self.slideSpeed=0.0
  32. self.vel=Vec3(0.0, 0.0, 0.0)
  33. self.stopThisFrame = 0
  34. def setWalkSpeed(self, forward, jump, reverse, rotate):
  35. assert self.debugPrint("setWalkSpeed()")
  36. self.avatarControlForwardSpeed=forward
  37. #self.avatarControlJumpForce=jump
  38. self.avatarControlReverseSpeed=reverse
  39. self.avatarControlRotateSpeed=rotate
  40. def getSpeeds(self):
  41. #assert self.debugPrint("getSpeeds()")
  42. return (self.speed, self.rotationSpeed, self.slideSpeed)
  43. def setAvatar(self, avatar):
  44. self.avatar = avatar
  45. if avatar is not None:
  46. pass # setup the avatar
  47. def setAirborneHeightFunc(self, getAirborneHeight):
  48. self.getAirborneHeight = getAirborneHeight
  49. def setWallBitMask(self, bitMask):
  50. self.cSphereBitMask = bitMask
  51. def setFloorBitMask(self, bitMask):
  52. self.cRayBitMask = bitMask
  53. def initializeCollisions(self, collisionTraverser, avatarNodePath,
  54. avatarRadius = 1.4, floorOffset = 1.0, reach = 1.0):
  55. """
  56. Set up the avatar for collisions
  57. """
  58. assert not avatarNodePath.isEmpty()
  59. self.cTrav = collisionTraverser
  60. self.avatarNodePath = avatarNodePath
  61. # Set up the collision sphere
  62. # This is a sphere on the ground to detect barrier collisions
  63. self.cSphere = CollisionSphere(0.0, 0.0, 0.0, avatarRadius)
  64. cSphereNode = CollisionNode('NPW.cSphereNode')
  65. cSphereNode.addSolid(self.cSphere)
  66. self.cSphereNodePath = avatarNodePath.attachNewNode(cSphereNode)
  67. cSphereNode.setFromCollideMask(self.cSphereBitMask)
  68. cSphereNode.setIntoCollideMask(BitMask32.allOff())
  69. # Set up the collison ray
  70. # This is a ray cast from your head down to detect floor polygons.
  71. # This ray start is arbitrarily high in the air. Feel free to use
  72. # a higher or lower value depending on whether you want an avatar
  73. # that is outside of the world to step up to the floor when they
  74. # get under valid floor:
  75. self.cRay = CollisionRay(0.0, 0.0, CollisionHandlerRayStart, 0.0, 0.0, -1.0)
  76. cRayNode = CollisionNode('NPW.cRayNode')
  77. cRayNode.addSolid(self.cRay)
  78. self.cRayNodePath = avatarNodePath.attachNewNode(cRayNode)
  79. cRayNode.setFromCollideMask(self.cRayBitMask)
  80. cRayNode.setIntoCollideMask(BitMask32.allOff())
  81. # set up wall collision mechanism
  82. self.pusher = CollisionHandlerPusher()
  83. self.pusher.setInPattern("enter%in")
  84. self.pusher.setOutPattern("exit%in")
  85. # set up floor collision mechanism
  86. self.lifter = CollisionHandlerFloor()
  87. self.lifter.setInPattern("on-floor")
  88. self.lifter.setOutPattern("off-floor")
  89. self.lifter.setOffset(floorOffset)
  90. self.lifter.setReach(reach)
  91. # Limit our rate-of-fall with the lifter.
  92. # If this is too low, we actually "fall" off steep stairs
  93. # and float above them as we go down. I increased this
  94. # from 8.0 to 16.0 to prevent this
  95. self.lifter.setMaxVelocity(16.0)
  96. self.pusher.addCollider(self.cSphereNodePath, avatarNodePath)
  97. self.lifter.addCollider(self.cRayNodePath, avatarNodePath)
  98. # activate the collider with the traverser and pusher
  99. self.setCollisionsActive(1)
  100. def deleteCollisions(self):
  101. del self.cTrav
  102. del self.cSphere
  103. self.cSphereNodePath.removeNode()
  104. del self.cSphereNodePath
  105. del self.cRay
  106. self.cRayNodePath.removeNode()
  107. del self.cRayNodePath
  108. del self.pusher
  109. del self.lifter
  110. def setTag(self, key, value):
  111. self.cSphereNodePath.setTag(key, value)
  112. def setCollisionsActive(self, active = 1):
  113. assert self.debugPrint("setCollisionsActive(active%s)"%(active,))
  114. if self.collisionsActive != active:
  115. self.collisionsActive = active
  116. if active:
  117. self.cTrav.addCollider(self.cSphereNodePath, self.pusher)
  118. self.cTrav.addCollider(self.cRayNodePath, self.lifter)
  119. else:
  120. self.cTrav.removeCollider(self.cSphereNodePath)
  121. self.cTrav.removeCollider(self.cRayNodePath)
  122. # Now that we have disabled collisions, make one more pass
  123. # right now to ensure we aren't standing in a wall.
  124. self.oneTimeCollide()
  125. def placeOnFloor(self):
  126. """
  127. Make a reasonable effor to place the avatar on the ground.
  128. For example, this is useful when switching away from the
  129. current walker.
  130. """
  131. # With these on, getAirborneHeight is not returning the correct value so
  132. # when we open our book while swimming we pop down underneath the ground
  133. # self.oneTimeCollide()
  134. # self.avatarNodePath.setZ(self.avatarNodePath.getZ()-self.getAirborneHeight())
  135. # Since this is the non physics walker - wont they already be on the ground?
  136. return
  137. def oneTimeCollide(self):
  138. """
  139. Makes one quick collision pass for the avatar, for instance as
  140. a one-time straighten-things-up operation after collisions
  141. have been disabled.
  142. """
  143. tempCTrav = CollisionTraverser("oneTimeCollide")
  144. tempCTrav.addCollider(self.cSphereNodePath, self.pusher)
  145. tempCTrav.addCollider(self.cRayNodePath, self.lifter)
  146. tempCTrav.traverse(render)
  147. def addBlastForce(self, vector):
  148. pass
  149. def displayDebugInfo(self):
  150. """
  151. For debug use.
  152. """
  153. onScreenDebug.add("controls", "NonPhysicsWalker")
  154. def _calcSpeeds(self):
  155. # get the button states:
  156. forward = inputState.isSet("forward")
  157. reverse = inputState.isSet("reverse")
  158. turnLeft = inputState.isSet("turnLeft")
  159. turnRight = inputState.isSet("turnRight")
  160. slide = inputState.isSet(self.slideName) or 0
  161. #jump = inputState.isSet("jump")
  162. # Determine what the speeds are based on the buttons:
  163. self.speed=(forward and self.avatarControlForwardSpeed or
  164. reverse and -self.avatarControlReverseSpeed)
  165. # Should fSlide be renamed slideButton?
  166. self.slideSpeed=slide and ((reverse and turnLeft and -self.avatarControlReverseSpeed*(0.75)) or
  167. (reverse and turnRight and self.avatarControlReverseSpeed*(0.75)) or
  168. (turnLeft and -self.avatarControlForwardSpeed*(0.75)) or
  169. (turnRight and self.avatarControlForwardSpeed*(0.75)))
  170. self.rotationSpeed=not slide and (
  171. (turnLeft and self.avatarControlRotateSpeed) or
  172. (turnRight and -self.avatarControlRotateSpeed))
  173. def handleAvatarControls(self, task):
  174. """
  175. Check on the arrow keys and update the avatar.
  176. """
  177. if not self.lifter.hasContact():
  178. # hack fix for falling through the floor:
  179. messenger.send("walkerIsOutOfWorld", [self.avatarNodePath])
  180. self._calcSpeeds()
  181. if __debug__:
  182. debugRunning = inputState.isSet("debugRunning")
  183. if debugRunning:
  184. self.speed*=4.0
  185. self.slideSpeed*=4.0
  186. self.rotationSpeed*=1.25
  187. if self.wantDebugIndicator:
  188. self.displayDebugInfo()
  189. # How far did we move based on the amount of time elapsed?
  190. dt=ClockObject.getGlobalClock().getDt()
  191. # Check to see if we're moving at all:
  192. if self.speed or self.slideSpeed or self.rotationSpeed:
  193. if self.stopThisFrame:
  194. distance = 0.0
  195. slideDistance = 0.0
  196. rotation = 0.0
  197. self.stopThisFrame = 0
  198. else:
  199. distance = dt * self.speed
  200. slideDistance = dt * self.slideSpeed
  201. rotation = dt * self.rotationSpeed
  202. # Take a step in the direction of our previous heading.
  203. self.vel=Vec3(Vec3.forward() * distance +
  204. Vec3.right() * slideDistance)
  205. if self.vel != Vec3.zero():
  206. # rotMat is the rotation matrix corresponding to
  207. # our previous heading.
  208. rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
  209. step=rotMat.xform(self.vel)
  210. self.avatarNodePath.setFluidPos(Point3(self.avatarNodePath.getPos()+step))
  211. self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
  212. messenger.send("avatarMoving")
  213. else:
  214. self.vel.set(0.0, 0.0, 0.0)
  215. self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
  216. self.__oldDt = dt
  217. self.worldVelocity = self.__oldPosDelta*(1/self.__oldDt)
  218. return Task.cont
  219. def doDeltaPos(self):
  220. assert self.debugPrint("doDeltaPos()")
  221. def reset(self):
  222. assert self.debugPrint("reset()")
  223. def getVelocity(self):
  224. return self.vel
  225. def enableAvatarControls(self):
  226. """
  227. Activate the arrow keys, etc.
  228. """
  229. assert self.debugPrint("enableAvatarControls")
  230. assert self.collisionsActive
  231. taskName = "AvatarControls-%s"%(id(self),)
  232. # remove any old
  233. taskMgr.remove(taskName)
  234. # spawn the new task
  235. taskMgr.add(self.handleAvatarControls, taskName)
  236. def disableAvatarControls(self):
  237. """
  238. Ignore the arrow keys, etc.
  239. """
  240. assert self.debugPrint("disableAvatarControls")
  241. taskName = "AvatarControls-%s"%(id(self),)
  242. taskMgr.remove(taskName)
  243. if __debug__:
  244. def debugPrint(self, message):
  245. """for debugging"""
  246. return self.notify.debug(
  247. str(id(self))+' '+message)