main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #!/usr/bin/env python
  2. # Author: Ryan Myers
  3. # Models: Jeff Styers, Reagan Heller
  4. #
  5. # Last Updated: 2015-03-13
  6. #
  7. # This tutorial provides an example of creating a character
  8. # and having it walk around on uneven terrain, as well
  9. # as implementing a fully rotatable camera.
  10. from direct.showbase.ShowBase import ShowBase
  11. from panda3d.core import CollisionTraverser, CollisionNode
  12. from panda3d.core import CollisionHandlerQueue, CollisionRay
  13. from panda3d.core import Filename, AmbientLight, DirectionalLight
  14. from panda3d.core import PandaNode, NodePath, Camera, TextNode
  15. from panda3d.core import CollideMask
  16. from direct.gui.OnscreenText import OnscreenText
  17. from direct.actor.Actor import Actor
  18. import random
  19. import sys
  20. import os
  21. import math
  22. # Function to put instructions on the screen.
  23. def addInstructions(pos, msg):
  24. return OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), scale=.05,
  25. shadow=(0, 0, 0, 1), parent=base.a2dTopLeft,
  26. pos=(0.08, -pos - 0.04), align=TextNode.ALeft)
  27. # Function to put title on the screen.
  28. def addTitle(text):
  29. return OnscreenText(text=text, style=1, fg=(1, 1, 1, 1), scale=.07,
  30. parent=base.a2dBottomRight, align=TextNode.ARight,
  31. pos=(-0.1, 0.09), shadow=(0, 0, 0, 1))
  32. class RoamingRalphDemo(ShowBase):
  33. def __init__(self):
  34. # Set up the window, camera, etc.
  35. ShowBase.__init__(self)
  36. # Set the background color to black
  37. self.win.setClearColor((0, 0, 0, 1))
  38. # This is used to store which keys are currently pressed.
  39. self.keyMap = {
  40. "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0}
  41. # Post the instructions
  42. self.title = addTitle(
  43. "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
  44. self.inst1 = addInstructions(0.06, "[ESC]: Quit")
  45. self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
  46. self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
  47. self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
  48. self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left")
  49. self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right")
  50. # Set up the environment
  51. #
  52. # This environment model contains collision meshes. If you look
  53. # in the egg file, you will see the following:
  54. #
  55. # <Collide> { Polyset keep descend }
  56. #
  57. # This tag causes the following mesh to be converted to a collision
  58. # mesh -- a mesh which is optimized for collision, not rendering.
  59. # It also keeps the original mesh, so there are now two copies ---
  60. # one optimized for rendering, one for collisions.
  61. self.environ = loader.loadModel("models/world")
  62. self.environ.reparentTo(render)
  63. # Create the main character, Ralph
  64. ralphStartPos = self.environ.find("**/start_point").getPos()
  65. self.ralph = Actor("models/ralph",
  66. {"run": "models/ralph-run",
  67. "walk": "models/ralph-walk"})
  68. self.ralph.reparentTo(render)
  69. self.ralph.setScale(.2)
  70. self.ralph.setPos(ralphStartPos + (0, 0, 0.5))
  71. # Create a floater object, which floats 2 units above ralph. We
  72. # use this as a target for the camera to look at.
  73. self.floater = NodePath(PandaNode("floater"))
  74. self.floater.reparentTo(self.ralph)
  75. self.floater.setZ(2.0)
  76. # Accept the control keys for movement and rotation
  77. self.accept("escape", sys.exit)
  78. self.accept("arrow_left", self.setKey, ["left", True])
  79. self.accept("arrow_right", self.setKey, ["right", True])
  80. self.accept("arrow_up", self.setKey, ["forward", True])
  81. self.accept("a", self.setKey, ["cam-left", True])
  82. self.accept("s", self.setKey, ["cam-right", True])
  83. self.accept("arrow_left-up", self.setKey, ["left", False])
  84. self.accept("arrow_right-up", self.setKey, ["right", False])
  85. self.accept("arrow_up-up", self.setKey, ["forward", False])
  86. self.accept("a-up", self.setKey, ["cam-left", False])
  87. self.accept("s-up", self.setKey, ["cam-right", False])
  88. taskMgr.add(self.move, "moveTask")
  89. # Game state variables
  90. self.isMoving = False
  91. # Set up the camera
  92. self.disableMouse()
  93. self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)
  94. # We will detect the height of the terrain by creating a collision
  95. # ray and casting it downward toward the terrain. One ray will
  96. # start above ralph's head, and the other will start above the camera.
  97. # A ray may hit the terrain, or it may hit a rock or a tree. If it
  98. # hits the terrain, we can detect the height. If it hits anything
  99. # else, we rule that the move is illegal.
  100. self.cTrav = CollisionTraverser()
  101. self.ralphGroundRay = CollisionRay()
  102. self.ralphGroundRay.setOrigin(0, 0, 9)
  103. self.ralphGroundRay.setDirection(0, 0, -1)
  104. self.ralphGroundCol = CollisionNode('ralphRay')
  105. self.ralphGroundCol.addSolid(self.ralphGroundRay)
  106. self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
  107. self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
  108. self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
  109. self.ralphGroundHandler = CollisionHandlerQueue()
  110. self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)
  111. self.camGroundRay = CollisionRay()
  112. self.camGroundRay.setOrigin(0, 0, 9)
  113. self.camGroundRay.setDirection(0, 0, -1)
  114. self.camGroundCol = CollisionNode('camRay')
  115. self.camGroundCol.addSolid(self.camGroundRay)
  116. self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
  117. self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
  118. self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
  119. self.camGroundHandler = CollisionHandlerQueue()
  120. self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
  121. # Uncomment this line to see the collision rays
  122. #self.ralphGroundColNp.show()
  123. #self.camGroundColNp.show()
  124. # Uncomment this line to show a visual representation of the
  125. # collisions occuring
  126. #self.cTrav.showCollisions(render)
  127. # Create some lighting
  128. ambientLight = AmbientLight("ambientLight")
  129. ambientLight.setColor((.3, .3, .3, 1))
  130. directionalLight = DirectionalLight("directionalLight")
  131. directionalLight.setDirection((-5, -5, -5))
  132. directionalLight.setColor((1, 1, 1, 1))
  133. directionalLight.setSpecularColor((1, 1, 1, 1))
  134. render.setLight(render.attachNewNode(ambientLight))
  135. render.setLight(render.attachNewNode(directionalLight))
  136. # Records the state of the arrow keys
  137. def setKey(self, key, value):
  138. self.keyMap[key] = value
  139. # Accepts arrow keys to move either the player or the menu cursor,
  140. # Also deals with grid checking and collision detection
  141. def move(self, task):
  142. # Get the time that elapsed since last frame. We multiply this with
  143. # the desired speed in order to find out with which distance to move
  144. # in order to achieve that desired speed.
  145. dt = globalClock.getDt()
  146. # If the camera-left key is pressed, move camera left.
  147. # If the camera-right key is pressed, move camera right.
  148. if self.keyMap["cam-left"]:
  149. self.camera.setX(self.camera, -20 * dt)
  150. if self.keyMap["cam-right"]:
  151. self.camera.setX(self.camera, +20 * dt)
  152. # save ralph's initial position so that we can restore it,
  153. # in case he falls off the map or runs into something.
  154. startpos = self.ralph.getPos()
  155. # If a move-key is pressed, move ralph in the specified direction.
  156. if self.keyMap["left"]:
  157. self.ralph.setH(self.ralph.getH() + 300 * dt)
  158. if self.keyMap["right"]:
  159. self.ralph.setH(self.ralph.getH() - 300 * dt)
  160. if self.keyMap["forward"]:
  161. self.ralph.setY(self.ralph, -25 * dt)
  162. # If ralph is moving, loop the run animation.
  163. # If he is standing still, stop the animation.
  164. if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"]:
  165. if self.isMoving is False:
  166. self.ralph.loop("run")
  167. self.isMoving = True
  168. else:
  169. if self.isMoving:
  170. self.ralph.stop()
  171. self.ralph.pose("walk", 5)
  172. self.isMoving = False
  173. # If the camera is too far from ralph, move it closer.
  174. # If the camera is too close to ralph, move it farther.
  175. camvec = self.ralph.getPos() - self.camera.getPos()
  176. camvec.setZ(0)
  177. camdist = camvec.length()
  178. camvec.normalize()
  179. if camdist > 10.0:
  180. self.camera.setPos(self.camera.getPos() + camvec * (camdist - 10))
  181. camdist = 10.0
  182. if camdist < 5.0:
  183. self.camera.setPos(self.camera.getPos() - camvec * (5 - camdist))
  184. camdist = 5.0
  185. # Normally, we would have to call traverse() to check for collisions.
  186. # However, the class ShowBase that we inherit from has a task to do
  187. # this for us, if we assign a CollisionTraverser to self.cTrav.
  188. #self.cTrav.traverse(render)
  189. # Adjust ralph's Z coordinate. If ralph's ray hit terrain,
  190. # update his Z. If it hit anything else, or didn't hit anything, put
  191. # him back where he was last frame.
  192. entries = list(self.ralphGroundHandler.getEntries())
  193. entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
  194. if len(entries) > 0 and entries[0].getIntoNode().getName() == "terrain":
  195. self.ralph.setZ(entries[0].getSurfacePoint(render).getZ())
  196. else:
  197. self.ralph.setPos(startpos)
  198. # Keep the camera at one foot above the terrain,
  199. # or two feet above ralph, whichever is greater.
  200. entries = list(self.camGroundHandler.getEntries())
  201. entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
  202. if len(entries) > 0 and entries[0].getIntoNode().getName() == "terrain":
  203. self.camera.setZ(entries[0].getSurfacePoint(render).getZ() + 1.0)
  204. if self.camera.getZ() < self.ralph.getZ() + 2.0:
  205. self.camera.setZ(self.ralph.getZ() + 2.0)
  206. # The camera should look in ralph's direction,
  207. # but it should also try to stay horizontal, so look at
  208. # a floater which hovers above ralph's head.
  209. self.camera.lookAt(self.floater)
  210. return task.cont
  211. demo = RoamingRalphDemo()
  212. demo.run()