Simple first person game base

I made a simple first person camera. Thank you to Thaumaturge for helping me figure out how to move objects based on the rotation.
I also got a bit of inspiration from here: First Person Camera

w, a, s, and d to move and use the mouse to look around.

from direct.showbase.ShowBase import ShowBase
from panda3d.core import *
from pandac.PandaModules import WindowProperties


sensitivity = 19



class MyApp(ShowBase):
	def camControl(self, task):

		# Mouse controls
		mw = base.mouseWatcherNode
		if mw.hasMouse():
			
			x = mw.getMouseX()
			y = mw.getMouseY()

			if not x == 0:
				self.body.setH(self.body.getH() + (-x) * sensitivity)
			
			if base.cam.getP() < 90 and base.cam.getP() > -90:
				base.cam.setP(base.cam.getP() + y * sensitivity)
			# If the camera is at a -90 or 90 degree angle, this code helps it not get stuck.
			else:
				if base.cam.getP() > 90:
					base.cam.setP(base.cam.getP() - 1)
				elif base.cam.getP() < -90:
					base.cam.setP(base.cam.getP() + 1)

			base.win.movePointer(0, int(base.win.getProperties().getXSize() / 2), int(base.win.getProperties().getYSize() / 2))
		# Mouse controls

		# Keyboard controls
		if keymap["w"]:
			self.body.setY(self.body, 3)

		if keymap["a"]:
			self.body.setX(self.body, -2)

		if keymap["s"]:
			self.body.setY(self.body, -3)

		if keymap["d"]:
			self.body.setX(self.body, 2)

		
		return task.cont
	def setKey(self, key, val):
		keymap[key] = val


	def __init__(self):
		ShowBase.__init__(self)

		props = WindowProperties()
		props.setCursorHidden(True)
		base.win.requestProperties(props)

		self.scene = loader.loadModel("environment")

		self.scene.reparentTo(self.render)

		global keymap
		keymap = {"w":False, "a":False, "s":False, "d":False}

		base.taskMgr.add(self.camControl, "cam")

		# Key accepts
		base.accept("w", self.setKey, ["w", True])
		base.accept("w-up", self.setKey, ["w", False])
		base.accept("a", self.setKey, ["a", True])
		base.accept("a-up", self.setKey, ["a", False])
		base.accept("s", self.setKey, ["s", True])
		base.accept("s-up", self.setKey, ["s", False])
		base.accept("d", self.setKey, ["d", True])
		base.accept("d-up", self.setKey, ["d", False])
	
		# Camera peranting
		self.body = render.attachNewNode("body")
		base.cam.reparentTo(self.body)


app = MyApp()
app.run()
1 Like

An interesting choice.

		global keymap
		keymap = {"w":False, "a":False, "s":False, "d":False}

You can do so.

self.keymap = {"w":False, "a":False, "s":False, "d":False}

I also recommend moving, rotating, and so on with:

sensitivity*globalClock.getDt ()
1 Like