本文整理汇总了Python中GameLogic类的典型用法代码示例。如果您正苦于以下问题:Python GameLogic类的具体用法?Python GameLogic怎么用?Python GameLogic使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GameLogic类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: findSceneByName
def findSceneByName(sceneName):
if sceneName == "":
return GameLogic.getCurrentScene()
for scene in GameLogic.getSceneList():
if scene.name == sceneName:
return scene
raise LookupError(("No active scene with name '%s' found"
% (sceneName)))
示例2: avoidanceVector
def avoidanceVector(self,fear):
'''find an vector that will avoid a named object in
the current scene
'''
if not fear in GameLogic.getCurrentScene().objects:
return Vector((0,0)) # object was not found
fearObj = GameLogic.getCurrentScene().objects[fear]
fearPos = fearObj.worldPosition.copy()
theta = atan2(self.worldPosition[1] - fearPos.y,self.worldPosition[0] - fearPos.x)
return(Vector((cos(theta),sin(theta))))
示例3: avoid
def avoid(self):
p1 = self.worldPosition.copy()
p1.z = 0
result = self.blank.copy()
for sheep in self.flock:
p2 = sheep.worldPosition.copy()
p2.z = 0
dist = (p1 - p2).magnitude
angle = atan2(p1.y - p2.y,p1.x - p2.x)
if 0 < dist < self.r1:
size = 1/dist**2
result.x = result.x + size*cos(angle)
result.y = result.y + size*sin(angle)
try: #Will fail if there is no ram.
ram = GameLogic.getCurrentScene().objects['ram']
p2 = ram.worldPosition.copy()
p2.z = 0
dist = (p1 - p2).magnitude
angle = atan2(p1.y - p2.y,p1.x - p2.x)
if 0 < dist < 1.5*self.r1:
size = 1.5/dist**2
result.x = result.x + size*cos(angle)
result.y = result.y + size*sin(angle)
except:
pass
result = result + self.avoidStatic()
tractor = GameLogic.getCurrentScene().objects['tractor']
p2 = tractor.worldPosition.copy()
p2.z = 0
dist = (p1 - p2).magnitude
angle = atan2(p1.y - p2.y,p1.x - p2.x)
if 0 < dist < 3*self.r1:
size = 5/dist**2
result.x = result.x + size*cos(angle)
result.y = result.y + size*sin(angle)
if result.magnitude > 0.05:
self.run()
result.normalize()
return result
if result.magnitude > 0.04:
self.flounder()
else:
self.walk()
result.normalize()
return result
示例4: onMouse
def onMouse():
Rasterizer.showMouse(True)
cont = GameLogic.getCurrentController()
mouse = cont.sensors["Mouse"]
over = cont.sensors["Over"]
if mouse.positive:
hit = over.hitObject
if hit is None:
return
print(hit.name)
print(hit.children)
if hit.name in buildings:
deselectAll()
hit.children["Base01.Selected"].setVisible(True)
infoPanelShow(hit)
addUnit()
else:
if hit.name in units:
deselectAll()
hit.children["Unit0.Selected"].setVisible(True)
cont.owner["selected"] = hit["id"]
infoPanelShow(hit)
else:
for target in scene.objects:
if "Target" in target.name and target["id"] == cont.owner["selected"]:
target.localPosition = over.hitPosition
示例5: update_robots
def update_robots(self):
"""
Update robots' poses in the HLA federation for multinode synchronization.
"""
self.morse_ambassador.tag = False
scene = GameLogic.getCurrentScene()
t = self.morse_ambassador.current_time + self.morse_ambassador.lookahead
for obj in self.morse_ambassador.objects:
obj_name = self.rtia.getObjectInstanceName(obj)
obj_pos = scene.objects[obj_name].worldPosition.to_tuple()
obj_ori = scene.objects[obj_name].worldOrientation.to_euler()
hla_att = {
self.morse_ambassador.out_position:
MorseVector.pack([obj_pos[0], obj_pos[1], obj_pos[2]]),
self.morse_ambassador.out_orientation:
MorseVector.pack([obj_ori.x, obj_ori.y, obj_ori.z])}
try:
self.rtia.updateAttributeValues(obj, hla_att, "update", t)
except rti.InvalidFederationTime:
logger.debug("Invalid time for UAV: %s; Federation time is %s",
t, self.rtia.queryFederateTime())
if self.certi_env["TimeRegulation"]:
self.rtia.timeAdvanceRequest(t)
while (not self.morse_ambassador.tag):
self.rtia.tick(0, 1)
scene.objects["HLA_Empty"]["Time"] = self.morse_ambassador.current_time
else:
self.rtia.tick()
示例6: configureHLA
def configureHLA(self):
"""
Configure the HLA network environment.
Uses the Game Properties of the HLA_Empty object if defined,
default values otherwise.
"""
logger.info("Initializing configuration")
if os.getenv("CERTI_HTTP_PROXY") == None:
os.environ["CERTI_HTTP_PROXY"] = ""
logger.debug("CERTI_HTTP_PROXY= %s", os.environ["CERTI_HTTP_PROXY"])
try:
hla = GameLogic.getCurrentScene().objects["HLA_Empty"]
for k in self.certi_env.keys():
try:
v = hla[k]
self.certi_env[k] = v
logger.debug("%s= %s", k, v)
except KeyError:
logger.debug("No property for %s; using %s", k,
self.certi_env[k])
except KeyError:
log.error("The HLA_Empty object has not been found on current scene!")
os.environ["CERTI_HOST"] = self.certi_env["CERTI_HOST"]
logger.debug("CERTI_HOST= %s", os.environ["CERTI_HOST"])
示例7: default_action
def default_action(self):
""" Look for nearby victims, and heal when instructed to """
# Look for victims in the cone of the sensor
contr = GameLogic.getCurrentController()
radar = contr.sensors['Radar']
if radar.triggered and radar.positive:
for victim_obj in radar.hitObjectList:
victim_position = victim_obj.worldPosition
self.local_data['victim_dict'][victim_obj.name] = [victim_position[0], victim_position[1], victim_position[2]]
# Find the closest victim and its distance
new_distance = self.blender_obj.getDistanceTo(victim_obj)
if new_distance < self._nearest_distance:
self._nearest_victim = victim_obj
self._nearest_distance = new_distance
# When instructed to do so, help a victim
if self._healing:
self._heal_victim()
if radar.triggered and not radar.positive:
# Clear the variables for the victims
self.local_data['victim_dict'] = {}
self._nearest_victim = None
self._nearest_distance = 999999
示例8: main
def main():
# Get owner
controller = GameLogic.getCurrentController()
owner = controller.owner
Host = 'localhost'
ServerPort = 10000
# Set socket server only one time at the first frame
if not owner['OneTime']:
# Set UDP socket
GameLogic.sServer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to host
GameLogic.sServer.bind((Host, ServerPort))
# If no data are found, pass
GameLogic.sServer.setblocking(0)
# Set prop to pass test
owner['OneTime'] = True
# Get Position and Orientation
PosCar = owner.worldPosition
OriCar = owner.worldOrientation
# New in python 3
stupid = (PosCar[0], PosCar[1], PosCar[2], OriCar[0][0], OriCar[0][1], OriCar[0][2], OriCar[1][0], OriCar[1][1], OriCar[1][2], OriCar[2][0], OriCar[2][1], OriCar[2][2])
print(stupid)
# Serialize data
Data = pickle.dumps(stupid)
# Send Data to client
GameLogic.sServer.sendto(Data, (Host, 10001))
示例9: reset_view
def reset_view(contr):
""" Make the human model look forward """
human = contr.owner
scene = GameLogic.getCurrentScene()
target = scene.objects['Target_Empty']
# Reset the Empty object to its original position
target.localPosition = [1.3, 0.0, 1.7]
示例10: grasp_
def grasp_(self, seq):
""" Grasp object.
"""
human = self.blender_obj
if human['Manipulate']:
scene = GameLogic.getCurrentScene()
hand_empty = scene.objects['Hand_Grab.R']
selected_object = hand_empty['Near_Object']
if seq == "t":
# Check that no other object is being carried
if (human['DraggedObject'] == None or
human['DraggedObject'] == '') :
# If the object is draggable
if selected_object != None and selected_object != '':
# Clear the previously selected object, if any
human['DraggedObject'] = selected_object
# Remove Physic simulation
selected_object.suspendDynamics()
# Parent the selected object to the hand target
selected_object.setParent (hand_empty)
if seq == "f":
if (human['DraggedObject'] != None and
human['DraggedObject'] != '') :
previous_object = human["DraggedObject"]
# Restore Physics simulation
previous_object.restoreDynamics()
previous_object.setLinearVelocity([0, 0, 0])
previous_object.setAngularVelocity([0, 0, 0])
# Remove the parent
previous_object.removeParent()
# Clear the object from dragged status
human['DraggedObject'] = None
示例11: main
def main():
if GameLogic.Object['closed']:
return
# get controller
controller = GameLogic.getCurrentController()
gu.keep_conn([conn1, conn2])
obj = controller.owner
pos = obj.localPosition
ori = obj.localOrientation
try:
arduino = serial.Serial('/dev/arduino_ethernet', 9600)
if x1_in <= pos[0] <= x_out and y_in <= pos[1] <= y_out:
arduino.write(b'A')
elif -x1_in >= pos[0] >= -x_out and -y_in >= pos[1] >= -y_out:
arduino.write(b'B')
else:
arduino.write(b'L')
except:
print("No reward")
if conn1 is not None:
# get mouse movement
t1, dt1, x1, y1 = gu.read32(conn1)
t2, dt2, x2, y2 = gu.read32(conn2)
else:
t1, dt1, x1, y1 = np.array([0,]), np.array([0,]), np.array([0,]), np.array([0,])
t2, dt2, x2, y2 = np.array([0,]), np.array([0,]), np.array([0,]), np.array([0,])
# move according to ball readout:
movement(controller, (x1, y1, x2, y2, t1, t2, dt1, dt2))
示例12: __init__
def __init__(self, obj, parent=None):
logger.info('%s initialization' % obj.name)
# Call the constructor of the parent class
super(self.__class__,self).__init__(obj, parent)
# Direction of the global vectors
self.world_X_vector = mathutils.Vector([1,0,0])
self.world_Y_vector = mathutils.Vector([0,1,0])
self._destination = self.blender_obj.position
self._wp_object = None
self._collisions = False
# Convert the direction tolerance to radians
self._angle_tolerance = math.radians(10)
# Choose the type of function to move the object
#self._type = 'Velocity'
self._type = 'Position'
self.local_data['x'] = self._destination[0]
self.local_data['y'] = self._destination[1]
self.local_data['z'] = self._destination[2]
# Waypoint tolerance (in meters)
self.local_data['tolerance'] = 0.5
# Read the speed from the Blender object properties
try:
self.local_data['speed'] = self.blender_obj['Speed']
logger.info("Using specified speed of %d" % self.local_data['speed'])
# Otherwise use a default value
except KeyError as detail:
self.local_data['speed'] = 1.0
logger.info("Using default speed of %d" % self.local_data['speed'])
# Identify an object as the target of the motion
try:
wp_name = self.blender_obj['Target']
if wp_name != '':
scene = GameLogic.getCurrentScene()
self._wp_object = scene.objects[wp_name]
logger.info("Using object '%s' to indicate motion target" % wp_name)
except KeyError as detail:
self._wp_object = None
# Identify the collision detectors for the sides
for child in self.blender_obj.children:
if "Radar.R" in child.name:
self._radar_r = child
if "Radar.L" in child.name:
self._radar_l = child
try:
logger.info("Radar Right is '%s'" % self._radar_r.name)
logger.info("Radar Left is '%s'" % self._radar_l.name)
self._collisions = True
except AttributeError as detail:
logger.warning("No radars found attached to the waypoint actuator.\n\tThere will be no obstacle avoidance")
logger.info('Component initialized')
示例13: default_action
def default_action(self):
""" Apply (x, y, w) to the parent robot. """
# Reset movement variables
vx, vy, vz = 0.0, 0.0, 0.0
rx, ry, rz = 0.0, 0.0, 0.0
# Tick rate is the real measure of time in Blender.
# By default it is set to 60, regardles of the FPS
# If logic tick rate is 60, then: 1 second = 60 ticks
ticks = GameLogic.getLogicTicRate()
# Scale the speeds to the time used by Blender
try:
vx = self.local_data['x'] / ticks
vy = self.local_data['y'] / ticks
rz = self.local_data['w'] / ticks
# For the moment ignoring the division by zero
# It happens apparently when the simulation starts
except ZeroDivisionError:
pass
# Get the Blender object of the parent robot
parent = self.robot_parent.blender_obj
# Give the movement instructions directly to the parent
# The second parameter specifies a "local" movement
parent.applyMovement([vx, vy, vz], True)
parent.applyRotation([rx, ry, rz], True)
示例14: quit
def quit():
""" Cleanly quit the simulation
"""
contr = GameLogic.getCurrentController()
main_close(contr)
main_terminate(contr)
示例15: main
def main(controller):
print("SpawnTest Begin")
owner = controller.owner
owner['scene'] = GameLogic.getCurrentScene()
print ('Scenes:', bge.logic.getSceneList())
objects = owner['scene'].objects
hidObjects = owner['scene'].objectsInactive
owner['cubePositioner'] = hidObjects["DataCubeRoot"]
owner['cuboidObject'] = hidObjects['Cuboid']
owner['cuboidText'] = hidObjects["DynamicText"]
#printSceneObjects(scene)
tmpPath = "C:\\Users\\Glen\\Dropbox\\GradProject\\randomCube.xml" #TODO: Change this to relative path
tableXMLPath = "C:\\Users\\Glen\\Dropbox\\GradProject\\DataTable.xml"
#dataCubeFromFile(tmpPath, hidObjects['Cuboid'], cuboidText, testDataCubePositioner, scene)
owner['dataTable'] = dataTableFromFile(tableXMLPath)
owner['tableIndex'] = indexDataTable(owner['dataTable'])
owner['dataCube'] = dataCubeFromDataTable(owner['dataTable'], owner['tableIndex'], 'All', owner['cuboidObject'], owner['cuboidText'], owner['cubePositioner'], owner['scene'])
#spawnDataCube(2, 2, 2, scene, hidObjects["Cuboid"], testDataCubePositioner)
#printSceneObjects(scene)
print("SpawnTest End")