HI, I’ve just been trying to make this program work. I’m unsure about quite a lot of things about Panda3D. It’s basically Asteroids without the bullets and actual asteroids. I also removed one of the functions at the beginning which helps create all the objects including the asteroids. If you could help me make it work it would be great thanks.
The models are the same as the asteroids game apart that the only model is the plane/ship related oe, same for the textures. Also, the background is now inexistent.
# Author: Shao Zhang, Phil Saltzman, and Greg Lindley
# Last Updated: 5/1/2005
#
# This tutorial demonstrates the use of tasks. A task is a function that gets
# called once every frame. They are good for things that need to be updated
# very often. In the case of asteriods, we use tasks to update the positions of
# all the objects, and to check if the bullets or the ship have hit the
# asteriods.
#
# Note: This definitely a complicated example. Tasks are the cores most games
# so it seemed appropriate to show what a full game in Panda could look like
import direct.directbase.DirectStart
from panda3d.core import TextNode
from panda3d.core import Point2,Point3,Vec3,Vec4
from direct.gui.OnscreenText import OnscreenText
from direct.showbase.DirectObject import DirectObject
from direct.task.Task import Task
from direct.actor.Actor import Actor
from math import sin, cos, pi
from random import randint, choice, random
import cPickle, sys
#Constants that will control the behavior of the game. It is good to group
#constants like this so that they can be changed once without having to find
#everywhere they are used in code
SPRITE_POS = 55 #At default field of view and a depth of 55, the screen
#dimensions is 40x30 units
SCREEN_X = 20 #Screen goes from -20 to 20 on X
SCREEN_Y = 15 #Screen goes from -15 to 15 on Y
TURN_RATE = 180 #Degrees ship can turn in 1 second
ACCELERATION = 10 #Ship acceleration in units/sec/sec
MAX_VEL = 6 #Maximum ship velocity in units/sec
MAX_VEL_SQ = MAX_VEL ** 2 #Square of the ship velocity
DEG_TO_RAD = pi/180 #translates degrees to radians for sin and cos
#Macro-like function used to reduce the amount to code needed to create the
#on screen instructions
def genLabelText(text, i):
return OnscreenText(text = text, pos = (-1.3, .95-.05*i), fg=(1,1,0,1),
align = TextNode.ALeft, scale = .05)
class World(DirectObject):
def __init__(self):
#This code puts the standard title and instruction text on screen
self.title = OnscreenText(text="Car Game",
style=1, fg=(1,1,0,1),
pos=(0.8,-0.95), scale = .07)
self.escapeText = genLabelText("ESC: Quit", 0)
self.leftkeyText = genLabelText("[Left Arrow]: Turn Left (CCW)", 1)
self.rightkeyText = genLabelText("[Right Arrow]: Turn Right (CW)", 2)
self.upkeyText = genLabelText("[Up Arrow]: Accelerate", 3)
base.disableMouse() #Disable default mouse-based camera control
self.ship = loader.loadModel("models/plane") #Every object uses the plane model
self.ship.reparentTo(camera) #Everything is parented to the camera so
#that it faces the screen
self.ship.setPos(2,3,0) #Set initial position
self.ship.setScale(0.2)
self.setVelocity(self.ship, Vec3(0,2,0)) #Initial velocity
#A dictionary of what keys are currently being pressed
#The key events update this list, and our task will query it as input
self.keys = {"turnLeft" : 0, "turnRight": 0,
"accel": 0}
self.accept("escape", sys.exit) #Escape quits
#Other keys events set the appropriate value in our key dictionary
self.accept("arrow_left", self.setKey, ["turnLeft", 1])
self.accept("arrow_left-up", self.setKey, ["turnLeft", 0])
self.accept("arrow_right", self.setKey, ["turnRight", 1])
self.accept("arrow_right-up", self.setKey, ["turnRight", 0])
self.accept("arrow_up", self.setKey, ["accel", 1])
self.accept("arrow_up-up", self.setKey, ["accel", 0])
#Now we create the task. taskMgr is the task manager that actually calls
#The function each frame. The add method creates a new task. The first
#argument is the function to be called, and the second argument is the name
#for the task. It returns a task object, that is passed to the function
#each frame
self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
#The task object is a good place to put variables that should stay
#persistant for the task function from frame to frame
self.gameTask.last = 0 #Task time of the last frame
self.alive = True
#As described earlier, this simply sets a key in the self.keys dictionary to
#the given value
def setKey(self, key, val): self.keys[key] = val
#############################################
#
# This version, using 'setTag', runs fine.
#
#############################################
def setVelocity(self, obj, val):
list = [val[0], val[1], val[2]]
obj.setTag("velocity", cPickle.dumps(list))
def getVelocity(self, obj):
list = cPickle.loads(obj.getTag("velocity"))
return Vec3(list[0], list[1], list[2])
def setExpires(self, obj, val):
obj.setTag("expires", str(val))
def getExpires(self, obj):
return float(obj.getTag("expires"))
#This is our main task function, which does all of the per-frame processing
#It takes in self like all functions in a class, and task, the task object
#returned by taskMgr
def gameLoop(self, task):
#task contains a variable time, which is the time in seconds the task has
#been running. By default, it does not have a delta time (or dt), which is
#the amount of time elapsed from the last frame. A common way to do this is
#to store the current time in task.last. This can be used to find dt
dt = task.time - task.last
task.last = task.time
#If the ship is not alive, do nothing. Tasks return Task.cont to signify
#that the task should continue running. If Task.done were returned instead,
#the task would be removed and would no longer be called every frame
if not self.alive: return Task.cont
#update ship position
self.updateShip(dt)
#check to see if the ship can fire
#Updates the positions of objects
def updatePos(self, obj, dt):
vel = self.getVelocity(obj)
newPos = obj.getPos() + (vel*dt)
#Check if the object is out of bounds. If so, wrap it
radius = .5 * obj.getScale().getX()
if newPos.getX() - radius > SCREEN_X: newPos.setX(-SCREEN_X)
elif newPos.getX() + radius < -SCREEN_X: newPos.setX(SCREEN_X)
if newPos.getZ() - radius > SCREEN_Y: newPos.setZ(-SCREEN_Y)
elif newPos.getZ() + radius < -SCREEN_Y: newPos.setZ(SCREEN_Y)
obj.setPos(newPos)
#This updates the ship's position. This is similar to the general update
#but takes into account turn and thrust
def updateShip(self, dt):
heading = self.ship.getR() #Heading is the roll value for this model
#Change heading if left or right is being pressed
if self.keys["turnRight"]:
heading += dt * TURN_RATE
self.ship.setR(heading %360)
elif self.keys["turnLeft"]:
heading -= dt * TURN_RATE
self.ship.setR(heading%360)
#Thrust causes acceleration in the direction the ship is currently facing
if self.keys["accel"]:
heading_rad = DEG_TO_RAD * heading
#This builds a new velocity vector and adds it to the current one
#Relative to the camera, the screen in Panda is the XZ plane.
#Therefore all of our Y values in our velocities are 0 to signify no
#change in that direction
newVel = (
Vec3(sin(heading_rad), 0, cos(heading_rad)) * ACCELERATION * dt)
newVel += self.getVelocity(self.ship)
#Clamps the new velocity to the maximum speed. lengthSquared() is used
#again since it is faster than length()
if newVel.lengthSquared() > MAX_VEL_SQ:
newVel.normalize()
newVel *= MAX_VEL
self.setVelocity(self.ship, newVel)
#Finally, update the position as with any other object
self.updatePos(self.ship, dt)
#We now have everything we need. Make an instance of the class and start
#3D rendering
w = World()
run()
Thanks for looking!