def motion_base():
    global velx, velxOld, vely, velyOld, velz, velzOld, host, port, send_address, s, rotVelx, rotVely, rotVelz
    cont = bge.logic.getCurrentController()
    own = cont.owner
    velocity = own.getLinearVelocity(1)
    rotVelocity = own.getAngularVelocity(1)
    rotVelx = rotVelocity[0]
    rotVely = rotVelocity[1]
    rotVelz = rotVelocity[2]
    # velx = velocity[0]
    # vely = velocity[1]
    velz = velocity[2]

    #this is a +90 degree rotation matrix about z
    velx = velocity[1]
    vely = -velocity[0]
    rotVelx = rotVelocity[1]
    rotVely = -rotVelocity[0]

    accelx = ((velx-velxOld) * logic.getAverageFrameRate()-vely*rotVelz+velz*rotVely)/9.8
    accely = ((vely-velyOld) * logic.getAverageFrameRate()+velx*rotVelz-velz*rotVelx)/9.8
    accelz = ((velz-velzOld) * logic.getAverageFrameRate()-velx*rotVely+vely*rotVelx)/9.8

    #send accelx
    velxOld = velx
    velyOld = vely
    velzOld = velz

    #print ("Acceleration: "+str(format(accelx,'0.4f'))+","+str(format(accely,'0.4f'))+","+str(format(accelz,'0.4f'))+ "\t" + "Angular Velocity: "+str(format(rotVelx,'0.4f'))+","+str(format(rotVely,'0.4f'))+","+str(format(rotVelz,'0.4f')))

    sendString = (str(format(accelx,'0.4f'))+","+str(format(accely,'0.4f'))+","+str(format(accelz,'0.4f'))+","+str(format(rotVelx,'0.4f'))+","+str(format(rotVely,'0.4f'))+","+str(format(rotVelz,'0.4f')))
    sentBytes = bytearray(sendString,'utf-8')
    s.sendto(sentBytes, send_address)
示例#2
0
def getAcc():
    lv = own.getLinearVelocity(True)
    try:
        own['acc'] = (abs(own['lastVel'] - getArrayProduct(lv)))
        try:
            if own['settled']:
                elapsedTime = 1 / logic.getAverageFrameRate()
                force = (
                    (abs(own['lastVel'] - getArrayProduct(lv)) / elapsedTime) /
                    100) + 1
                #print("force: "+str(force)+"\nelapsedTimie: "+str(elapsedTime))
                if own['armed']:
                    if logic.maxGForce < force:
                        logic.maxGForce = force
                        print(str(logic.maxGForce) + "G")
                else:
                    logic.maxGForce = 0
                logic.gForce = force
        except Exception as e:
            print(e)
            own['armed'] = False
            logic.gForce = 0
            logic.maxGForce = 0

        own['airSpeedDiff'] = (own['lastAirSpeedDiff'] - lv[2]) * 0.018
        own['lastVel'] = getArrayProduct(lv)
    except Exception as e:
        try:
            own['lastVel'] = getArrayProduct(lv)
            own['acc'] = abs(own['lastVel'] - getArrayProduct(lv))
            own['lastAirSpeedDiff'] = lv[2]
        except Exception as e:
            print(e)
示例#3
0
def isSettled(
):  #TO-DO get rid of all the settingling logic. The launch pads should be more stable now
    if not own['settled']:
        #logic.setTimeScale(0.001)
        if (flowState.getGameMode() == flowState.GAME_MODE_SINGLE_PLAYER):
            logic.isSettled = False
            fps = logic.getAverageFrameRate()
            avgFPSList = own['settleFrameRates']
            avgFPSList.append(fps)
            deviation = 100
            if (len(avgFPSList) > 1):
                deviation = statistics.stdev(avgFPSList)
            if len(avgFPSList) > 100:
                if deviation < 300:
                    settle()
            else:

                own.setLinearVelocity([0, 0, 0], True)
                own.position = own['launchPosition']
            if len(avgFPSList) > 1000:
                del avgFPSList[0]
                settle()
                flowState.log(
                    "WARNING!!!: FPS did not become stable after 2000 frames. Expect physics instability..."
                )
                flowState.log("standard deviation: " + str(deviation))
        else:  #we are in multiplayer and should wait a fixed time
            if ((time.perf_counter() - own['settleStartTime']) > 3):
                settle()
                flowState.log("settling due to time expiration in multiplayer")
示例#4
0
def isSettled():
    if not own['settled']:
        logic.setTimeScale(0.001)
        if(utils.getMode()!=utils.MODE_MULTIPLAYER):
            logic.isSettled = False
            fps = logic.getAverageFrameRate()
            avgFPSList = own['settleFrameRates']
            avgFPSList.append(fps)
            deviation = 100
            if(len(avgFPSList)>1):
                deviation = statistics.stdev(avgFPSList)
            if len(avgFPSList)>100:
                if deviation < 300:
                    settle()
            else:

                own.setLinearVelocity([0,0,0],True)
                own.position = own['launchPosition']
            if len(avgFPSList)>1000:
                del avgFPSList[0]
                settle()
                utils.log("WARNING!!!: FPS did not become stable after 2000 frames. Expect physics instability...")
                utils.log("standard deviation: "+str(deviation))
        else: #we are in multiplayer and should wait a fixed time
            if ((time.perf_counter()-own['settleStartTime'])>3):
                settle()
                utils.log("settling due to time expiration in multiplayer")
    else:
        if(logic.finishedLastLap):
            logic.setTimeScale(0.001)
    def move(self):
        key = logic.keyboard

        walk_direction = self.walk_direction
        walk_direction[:] = (0, 0, 0)
        speed = self.speed

        if key.events[events.WKEY]:
            walk_direction[1] = 1.0
        if key.events[events.SKEY]:
            walk_direction[1] = -1.0

        if key.events[events.DKEY]:
            walk_direction[0] = 1.0
        if key.events[events.AKEY]:
            walk_direction[0] = -1.0

        walk_direction.normalize()
        walk_direction *= speed

        if self.phys_id != 0:
            self.rotate_foot()

            footlocal = self.foot.localOrientation
            walk_direction[:] = footlocal * walk_direction
            walk_lz = walk_direction[2]
            velo_lz = self.getLinearVelocity(True)[2]

            ground = self.ground
            space = key.events[events.SPACEKEY]

            if ground or velo_lz < 3.0:
                self.jumping = False

            if self.jumping:
                if not space:
                    walk_direction[2] = velo_lz / 2
                    self.jumping = False
                else:
                    walk_direction[2] = velo_lz
            elif ground:
                if space:
                    walk_direction[2] += self.jump_speed
                    self.jumping = True
                else:
                    walk_direction -= footlocal.col[2]
            else:
                walk_direction[2] = velo_lz

            self.setLinearVelocity(walk_direction, True)
        else:
            if key.events[events.EKEY]:
                walk_direction[2] += speed
            if key.events[events.CKEY]:
                walk_direction[2] -= speed
            walk_direction /= logic.getAverageFrameRate()

            self.applyMovement(walk_direction, True)
    def move(self):
        key = logic.keyboard

        walk_direction = self.walk_direction
        walk_direction[:] = (0, 0, 0)
        speed = self.speed

        if key.events[events.WKEY]:
            walk_direction[1] = 1.0
        if key.events[events.SKEY]:
            walk_direction[1] = -1.0

        if key.events[events.DKEY]:
            walk_direction[0] = 1.0
        if key.events[events.AKEY]:
            walk_direction[0] = -1.0

        walk_direction.normalize()
        walk_direction *= speed

        if self.phys_id != 0:
            self.rotate_foot()

            footlocal = self.foot.localOrientation
            walk_direction[:] = footlocal * walk_direction
            walk_lz = walk_direction[2]
            velo_lz = self.getLinearVelocity(True)[2]

            ground = self.ground
            space = key.events[events.SPACEKEY]

            if ground or velo_lz < 3.0:
                self.jumping = False

            if self.jumping:
                if not space:
                    walk_direction[2] = velo_lz / 2
                    self.jumping = False
                else:
                    walk_direction[2] = velo_lz
            elif ground:
                if space:
                    walk_direction[2] += self.jump_speed
                    self.jumping = True
                else:
                    walk_direction -= footlocal.col[2]
            else:
                walk_direction[2] = velo_lz

            self.setLinearVelocity(walk_direction, True)
        else:
            if key.events[events.EKEY]:
                walk_direction[2] += speed
            if key.events[events.CKEY]:
                walk_direction[2] -= speed
            walk_direction /= logic.getAverageFrameRate()

            self.applyMovement(walk_direction, True)
示例#7
0
def motion_base():
    global velx, velxOld, vely, velyOld, velz, velzOld, host, port, send_address, s, rotVelx, rotVely, rotVelz
    cont = bge.logic.getCurrentController()
    own = cont.owner
    velocity = own.getLinearVelocity(1)
    rotVelocity = own.getAngularVelocity(1)
    rotVelx = rotVelocity[0]
    rotVely = rotVelocity[1]
    rotVelz = rotVelocity[2]
    # velx = velocity[0]
    # vely = velocity[1]
    velz = velocity[2]

    #this is a +90 degree rotation matrix about z
    velx = velocity[1]
    vely = -velocity[0]
    rotVelx = rotVelocity[1]
    rotVely = -rotVelocity[0]

    accelx = ((velx - velxOld) * logic.getAverageFrameRate() - vely * rotVelz +
              velz * rotVely) / 9.8
    accely = ((vely - velyOld) * logic.getAverageFrameRate() + velx * rotVelz -
              velz * rotVelx) / 9.8
    accelz = ((velz - velzOld) * logic.getAverageFrameRate() - velx * rotVely +
              vely * rotVelx) / 9.8

    #send accelx
    velxOld = velx
    velyOld = vely
    velzOld = velz

    #print ("Acceleration: "+str(format(accelx,'0.4f'))+","+str(format(accely,'0.4f'))+","+str(format(accelz,'0.4f'))+ "\t" + "Angular Velocity: "+str(format(rotVelx,'0.4f'))+","+str(format(rotVely,'0.4f'))+","+str(format(rotVelz,'0.4f')))

    sendString = (str(format(accelx, '0.4f')) + "," +
                  str(format(accely, '0.4f')) + "," +
                  str(format(accelz, '0.4f')) + "," +
                  str(format(rotVelx, '0.4f')) + "," +
                  str(format(rotVely, '0.4f')) + "," +
                  str(format(rotVelz, '0.4f')))
    sentBytes = bytearray(sendString, 'utf-8')
    s.sendto(sentBytes, send_address)
示例#8
0
def frameSleep():
	""" Forces a sleep time on BGE to make low-consiming games not melt the CPU. """
	global _nosleep, _3sleep
	avg = logic.getAverageFrameRate()
	if avg < 45: _3sleep = 3
	else: _3sleep = 0
	if avg < 30: _nosleep = True
	else: _nosleep = False

	if _sleeptime <= 0 or _nosleep == True: return
	if _3sleep > 1:
		_3sleep -= 1
		return
	if _3sleep == 1: _3sleep = 3

	sleep(_sleeptime)
示例#9
0
def frameSleep():
    """ Forces a sleep time on BGE to make low-consiming games not melt the CPU. """
    global _nosleep, _3sleep
    avg = logic.getAverageFrameRate()
    if avg < 45: _3sleep = 3
    else: _3sleep = 0
    if avg < 30: _nosleep = True
    else: _nosleep = False

    if _sleeptime <= 0 or _nosleep == True: return
    if _3sleep > 1:
        _3sleep -= 1
        return
    if _3sleep == 1: _3sleep = 3

    sleep(_sleeptime)
示例#10
0
def moveObjectToPosition(origin, dest, speed = 1):
	""" Moves *origin* to *dest* at a speed of *speed*. Must by called every frame for a complete movement.

	:param origin: Object to move.
	:type origin: |KX_GameObject|
	:param dest: Destination object.
	:type dest: |Vector|
	:param float speed: The amount of movment to do in one frame.
	:return: True if the object has been moved, false otherwise.
	"""
	fr = logic.getAverageFrameRate()
	if fr < 20: fr = 20
	vel = speed / fr
	vec = vectorFrom2Points(origin.position, dest, vel)
	if vec:
		origin.position += vec
		return True
	else: return False
示例#11
0
def moveObjectToPosition(origin, dest, speed = 1):
	""" Moves *origin* to *dest* at a speed of *speed*. Must by called every frame for a complete movement.

	:param origin: Object to move.
	:type origin: |KX_GameObject|
	:param dest: Destination object.
	:type dest: |Vector|
	:param float speed: The amount of movment to do in one frame.
	:return: True if the object has been moved, false otherwise.
	"""
	fr = logic.getAverageFrameRate()
	if fr < 20: fr = 20
	vel = speed / fr
	vec = vectorFrom2Points(origin.position, dest, vel)
	if vec:
		origin.position += vec
		return True
	else: return False
示例#12
0
def Sprite(spriteobj=None):
    """
    Animates the UV-coordinates of the object specified (or the object that the function is performed on) to draw a sprite.

    The average animation looks like:
    [0, 0, 1, 2, 3]
    Where the first value is the position of the animation's column, and the later ones are the frame numbers (going upwards)

    The only argument for this function is:

    spriteobj = Which sprite's UV-mesh to change; None or omitted = this object
    """

    sce = logic.getCurrentScene()
    cam = sce.active_camera

    cont = logic.getCurrentController()

    if spriteobj == None:
        obj = cont.owner
    else:
        obj = spriteobj

    frequency = cont.sensors[0].frequency + 1

    try:

        #obj['anim'] = [0, 0, 1, 0, 3]		# A test animation using the first column of the spritesheet, with the first, second, and fourth sprite sheet cells being used

        if obj[
            'sprcamoptimize']:                    # Optimization where if the sprite isn't on screen, it won't update every frame
            if cam.pointInsideFrustum(obj.position):
                cont.sensors[0].frequency = obj['sprfreqorig']
            else:
                cont.sensors[0].frequency = obj['sprfreqorig'] + 5

        if obj[
            'sprfpslock'] == 0:                    # Without FPS Locking on, the sprite will attempt to speed up when the game slows down and vise versa.
            fps = logic.getAverageFrameRate()
            if fps == 0.0:                        # At the game engine's initializing, getAverageFrameRate may return 0.0 because it samples the FPS over some time
                fps = logic.getLogicTicRate()

        else:                                    # With FPS Locking on, the sprite will animate regardless of FPS changes.
            fps = logic.getLogicTicRate()

        ## I'll generally only use exact squares (e.g. 4 64x64 subimages on a 256x256 image),
        ## but I've decided to go with both a width and height variable for uneven images.
        ## The number for each is obtained by dividing one by the total number of sprite
        ## frames available on the sprite sheet (the same either way to equal a square
        ## sheet). For example, if you can fit 4 images on a 64x64 image, and each
        ## sprite is equal-sized and takes up the most space, then you would end up with
        ## even 32x32 images, or images whose sizes equal 0.5 each way.

        sprfps = obj['sprfps'] / fps

        anim = obj['spranim']

        if anim != None:

            obj['sprpastsubimage'] = obj['sprsubimage']

            if obj['sprfps'] != 0.0:    # If spritefps == 0, don't advance the subimage
                obj['sprsubimage'] += round(sprfps,
                                            2) * frequency    # GameLogic's logic tic rate is constant, but if FPS drops below the tic rate, the animations won't adjust

            if math.floor(obj['sprsubimage']) > len(anim) - 1:
                if obj['sprfps'] > 0:
                    while obj['sprsubimage'] > (len(anim) - 1):
                        obj['sprsubimage'] -= (len(anim) - 1)
                else:
                    obj['sprsubimage'] = 1.0

            elif math.floor(obj[
                'sprsubimage']) < 1.0:    # Hack that makes sure the subimage is never looking at the animation column for a frame
                if obj['sprfps'] > 0:
                    obj[
                        'sprsubimage'] = 1.0        # Shouldn't really ever happen that the subimage is going up, but somehow goes below 0; if it does, just set it to a healthy 1.
                else:
                    while obj['sprsubimage'] < (len(anim) - 1):
                        obj['sprsubimage'] += (len(anim) - 1)

            if obj['sprsubimage'] < 1.0:
                obj['sprsubimage'] = 1.0
            if obj['sprsubimage'] > len(anim):
                obj['sprsubimage'] = len(anim) - 1

            subi = math.floor(obj['sprsubimage'])

            ## This below is pretty much the only way to get the info from the vertices
            ## When viewing a plane so that the sprite appears straight on:
            ## Vertex 0 = Top-Right
            ## Vertex 1 = Top-Left
            ## Vertex 2 = Bottom-Left
            ## Vertex 3 = Bottom-Right
            ## I believe this has to do with culling, which apparently takes place
            ## counter-clockwise here (?)

            vertex = [None, None, None, None]
            for a in range(4):
                vertex[a] = obj.meshes[obj['sprmat']].getVertex(obj['sprmesh'],
                                                                a)    # The sprite object's vertices; used only by the Sprite() function

            if obj['sprflipx'] == 0 and obj['sprflipy'] == 0:
                vertex[0].setUV([obj['sprh'] + (obj['sprh'] * anim[0]), obj['sprw'] + (obj['sprw'] * anim[subi])])
                vertex[1].setUV([obj['sprh'] * anim[0], obj['sprw'] + (obj['sprw'] * anim[subi])])
                vertex[2].setUV([obj['sprh'] * anim[0], obj['sprw'] * anim[subi]])
                vertex[3].setUV([obj['sprh'] + (obj['sprh'] * anim[0]), obj['sprw'] * anim[subi]])
            elif obj['sprflipx'] == 0 and obj['sprflipy'] == 1:
                vertex[3].setUV([obj['sprh'] + (obj['sprh'] * anim[0]), obj['sprw'] + (obj['sprw'] * anim[subi])])
                vertex[2].setUV([obj['sprh'] * anim[0], obj['sprw'] + (obj['sprw'] * anim[subi])])
                vertex[1].setUV([obj['sprh'] * anim[0], obj['sprw'] * anim[subi]])
                vertex[0].setUV([obj['sprh'] + (obj['sprh'] * anim[0]), obj['sprw'] * anim[subi]])
            elif obj['sprflipx'] == 1 and obj['sprflipy'] == 0:
                vertex[1].setUV([obj['sprh'] + (obj['sprh'] * anim[0]), obj['sprw'] + (obj['sprw'] * anim[subi])])
                vertex[0].setUV([obj['sprh'] * anim[0], obj['sprw'] + (obj['sprw'] * anim[subi])])
                vertex[3].setUV([obj['sprh'] * anim[0], obj['sprw'] * anim[subi]])
                vertex[2].setUV([obj['sprh'] + (obj['sprh'] * anim[0]), obj['sprw'] * anim[subi]])
            else:
                vertex[2].setUV([obj['sprh'] + (obj['sprh'] * anim[0]), obj['sprw'] + (obj['sprw'] * anim[subi])])
                vertex[3].setUV([obj['sprh'] * anim[0], obj['sprw'] + (obj['sprw'] * anim[subi])])
                vertex[0].setUV([obj['sprh'] * anim[0], obj['sprw'] * anim[subi]])
                vertex[1].setUV([obj['sprh'] + (obj['sprh'] * anim[0]), obj['sprw'] * anim[subi]])

            if obj[
                'sprrotate'] != None:                    # If you don't set the rotate value, then you're saying that you'll handle it.
                ori = obj['sprori'].copy()
                ori.y += obj['sprrotate']
                obj.orientation = ori

    except KeyError:    # Initialize the sprite object if it hasn't been initialized
        SpriteInit(obj)
示例#13
0
def SpriteMesh(spriteobj=None):
    """
        Replaces the mesh of the object specified (or the object that the function is performed on) to draw a sprite.
        The average sprite replacement animation looks like:
        ['Explosion', 0, 1, 2, 3]
        Where the first value is the name of the mesh to replace for the sprite, and the later values are the image numbers
        (going upwards), where each individual sprite mesh is named the first value, then a later one. An example would be that the
        first sprite of an explosion would be named 'Explosion0'.

        If the sprite seems to be animating slowly (not on time), it's probably because the Rasterizer is working extra hard to change the meshes.
        You can see this in the profiler.
        To fix this, ensure no modifiers are present on the mesh frames to replace.
        Also, if there's a slight lag between switching sprites, this is because the sprite frames have a lot of polygons, and so loading them into
        and out of memory is slowing the BGE down. To fix this, place the sprites somewhere in the game scene to keep them around in memory.

        See SpriteInit function for possible object variables to change.

        The only argument for this function is:

        spriteobj = Which sprite's UV-mesh to change; None or omitted = this object
    """

    from bge import logic
    import math

    sce = logic.getCurrentScene()
    cam = sce.active_camera

    cont = logic.getCurrentController()

    if spriteobj == None:
        obj = cont.owner
    else:
        obj = spriteobj

    if spriteobj == None:
        obj = cont.owner
    else:
        obj = spriteobj

    frequency = cont.sensors[0].frequency + 1

    try:

        if obj[
            'sprcamoptimize']:                    # Optimization where if the sprite isn't on screen, it won't update every frame
            if cam.pointInsideFrustum(obj.position):
                cont.sensors[0].frequency = obj['sprfreqorig']
            else:
                cont.sensors[0].frequency = obj['sprfreqorig'] + 5

        if obj[
            'sprfpslock'] == 0:                    # Without FPS Locking on, the sprite will attempt to speed up when the game slows down and vise versa.
            fps = logic.getAverageFrameRate()
            if fps == 0.0:                        # At the game engine's initializing, getAverageFrameRate may return 0.0 because it samples the FPS over some time
                fps = logic.getLogicTicRate()

        else:                                    # With FPS Locking on, the sprite will animate regardless of FPS changes.
            fps = logic.getLogicTicRate()

        ## I'll generally only use exact squares (e.g. 4 64x64 subimages on a 256x256 image),
        ## but I've decided to go with both a width and height variable for uneven images.
        ## The number for each is obtained by dividing one by the total number of sprite
        ## frames available on the sprite sheet (the same either way to equal a square
        ## sheet). For example, if you can fit 4 images on a 64x64 image, and each
        ## sprite is equal-sized and takes up the most space, then you would end up with
        ## even 32x32 images, or images whose sizes equal 0.5 each way.

        sprfps = obj['sprfps'] / fps

        anim = obj['spranim']

        if anim != None:

            obj['sprpastsubimage'] = obj['sprsubimage']

            if obj['sprfps'] != 0.0:    # If spritefps == 0, don't advance the subimage
                obj['sprsubimage'] += round(sprfps,
                                            2) * frequency    # GameLogic's logic tic rate is constant, but if FPS drops below the tic rate, the animations will adjust

            if math.floor(obj['sprsubimage']) > len(anim) - 1:
                if obj['sprfps'] > 0:
                    while obj['sprsubimage'] > (len(anim) - 1):
                        obj['sprsubimage'] -= (len(anim) - 1)
                else:
                    obj['sprsubimage'] = 1.0

            elif math.floor(obj[
                'sprsubimage']) < 1.0:    # Hack that makes sure the subimage is never looking at the animation column for a frame
                if obj['sprfps'] > 0:
                    obj[
                        'sprsubimage'] = 1.0        # Shouldn't really ever happen that the subimage is going up, but somehow goes below 0; if it does, just set it to a healthy 1.
                else:
                    while obj['sprsubimage'] < (len(anim) - 1):
                        obj['sprsubimage'] += (len(anim) - 1)

            if obj['sprsubimage'] < 1.0:
                obj['sprsubimage'] = 1.0
            if obj['sprsubimage'] > len(anim):
                obj['sprsubimage'] = len(anim) - 1

            subi = math.floor(obj['sprsubimage'])

            frame = anim[0] + str(anim[subi])

            if str(obj.meshes[
                0]) != frame:    # Only replace the mesh if the object's current mesh isn't equal to the one to use (if it's equal, then the mesh was replaced earlier)

                obj.replaceMesh(frame)

            ori = obj.worldOrientation.to_euler()

            if obj['sprflipx']:
                ori.z += math.pi

            if obj['sprflipy']:
                ori.x += math.pi

            if obj[
                'sprrotate'] != None:                    # If you set the rotate value, then you're saying that you'll handle it, so be aware of that
                ori.y += obj['sprrotate']

            obj.worldOrientation = ori

    except KeyError:    # Initialize the sprite object if it hasn't been initialized

        SpriteInit(obj)
示例#14
0
	def loop(self, scene):


		# update debug text
		if useDebug:
			try:
				t = ""
				for key, item in logic.watch.items():
					t += "%s: %s\n---------\n"%(key, item)
				self.debug.text = t

				# show number of BG process
				num = len(logic.registeredFunctions)
				if num <=0:
					self.bgProcessCounter.text = "Clean"
				elif num == 1:
					self.bgProcessCounter.text = "1 background process running"
				else:
					self.bgProcessCounter.text = str(num) + " background processes running"
			except:
				pass


			# show fps
			self.debug.text += '\n' + str(int(logic.getAverageFrameRate())) + ' fps'


		# Handle the mouse
		# hack needed since inactive window does not update mouse position
		if logic.mouseExitHack:
			pos = [0,0]				# set position to a harmless location
			# disable hack once mouse events are properly capturing again
			if logic.mousePosDelta[0] != 0 or logic.mousePosDelta[1] != 0:
				logic.mouseExitHack = False
		else:
			pos = list(logic.mouse.position)

		pos[0] *= render.getWindowWidth()
		pos[1] = render.getWindowHeight() * (1.0-pos[1])

		mouse_state = bgui.BGUI_MOUSE_NONE
		mouse_events = logic.mouse.events

		if mouse_events[events.LEFTMOUSE] == logic.KX_INPUT_JUST_ACTIVATED:
			mouse_state = bgui.BGUI_MOUSE_LEFT_CLICK
		elif mouse_events[events.LEFTMOUSE] == logic.KX_INPUT_JUST_RELEASED or logic.tap:
			mouse_state = bgui.BGUI_MOUSE_LEFT_RELEASE
		elif mouse_events[events.LEFTMOUSE] == logic.KX_INPUT_ACTIVE:
			mouse_state = bgui.BGUI_MOUSE_LEFT_ACTIVE
		elif mouse_events[events.RIGHTMOUSE] == logic.KX_INPUT_JUST_ACTIVATED:
			mouse_state = bgui.BGUI_MOUSE_RIGHT_CLICK
		elif mouse_events[events.RIGHTMOUSE] == logic.KX_INPUT_JUST_RELEASED:
			mouse_state = bgui.BGUI_MOUSE_RIGHT_RELEASE
		elif mouse_events[events.RIGHTMOUSE] == logic.KX_INPUT_ACTIVE:
			mouse_state = bgui.BGUI_MOUSE_RIGHT_ACTIVE
		elif mouse_events[events.WHEELUPMOUSE] == logic.KX_INPUT_JUST_ACTIVATED or mouse_events[events.WHEELUPMOUSE] == logic.KX_INPUT_ACTIVE or logic.mouseUp:
			mouse_state = bgui.BGUI_MOUSE_WHEEL_UP
		elif mouse_events[events.WHEELDOWNMOUSE] == logic.KX_INPUT_JUST_ACTIVATED or mouse_events[events.WHEELDOWNMOUSE] == logic.KX_INPUT_ACTIVE or logic.mouseDown:
			mouse_state = bgui.BGUI_MOUSE_WHEEL_DOWN

		logic.mouseUp = False
		logic.mouseDown = False
		logic.tap = False

		try:
			self.update_mouse(pos, mouse_state)
		except KeyError:
			pass

		self.mousePos = pos[:]

		# Handle the keyboard
		key_events = logic.keyboard.events

		is_shifted = 0 < key_events[events.LEFTSHIFTKEY] < 3 or \
					0 < key_events[events.RIGHTSHIFTKEY] < 3

		is_ctrled = 0 < key_events[events.LEFTCTRLKEY] < 3 or \
					0 < key_events[events.RIGHTCTRLKEY] < 3

		is_alted = 0 < key_events[events.LEFTALTKEY] < 3 or \
					0 < key_events[events.RIGHTALTKEY] < 3


		if 'mac' in releaseOS:
			is_commanded = 0 < key_events[events.OSKEY] < 3
		elif 'win' in releaseOS:
			is_commanded = False  # do not process WIndows OS keys (start)
		else:
			is_commanded = False  # other OS

		self.isCtrled = is_ctrled
		self.isAlted = is_alted
		self.isShifted = is_shifted
		self.isCommanded = is_commanded


		# to bgui, Command and Ctrl is one key
		for key, state in logic.keyboard.events.items():
			if state == logic.KX_INPUT_JUST_ACTIVATED:
				self.update_keyboard(self.keymap[key], is_shifted, is_ctrled or is_commanded)
				logic.keyCounter = -10 		# key repeat delay

			elif state == logic.KX_INPUT_ACTIVE:
				if logic.keyCounter % 2 == 0 and logic.keyCounter > 0:
					self.update_keyboard(self.keymap[key], is_shifted, is_ctrled or is_commanded)
				logic.keyCounter += 1 		# key repeat rate

		# Now setup the scene callback so we can draw
		scene.post_draw = [self.render]

		if useDebug and False:
			imp.reload(viewport)
			self.viewport = viewport.init(self)
示例#15
0
import bge.logic as logic
cont = logic.getCurrentController()
own = cont.owner
own['Text'] = logic.getAverageFrameRate()
示例#16
0
    def play(self, anim_name, reset_subimage_on_change=True):

        if not anim_name in self.anim_dict:

            print("ERROR: SpriteMap owner " + self.obj.name + " has no animation named " + anim_name + ".")

            return False

        elif len(self.anim_dict[anim_name]['animation']) < 2:

            print("ERROR: SpriteMap owner " + self.obj.name + "'s animation " + anim_name + " does not contain data "
                                                                                            "for at least one frame of "
                                                                                            "animation.")

            return False

        self.current_animation = anim_name

        if self.current_animation != self.prev_animation:

            self.on_animation_change(self, self.current_animation, self.prev_animation)  # Callback

            if reset_subimage_on_change:
                self.subimage = 1.0

        if self.adjust_by_sensor_frequency:
            freq = logic.getCurrentController().sensors[0].frequency + 1
        else:
            freq = 1

        if self.fps_lock:
            scene_fps = logic.getLogicTicRate()
        else:
            scene_fps = logic.getAverageFrameRate()
            if scene_fps == 0.0:
                scene_fps = logic.getLogicTicRate()

        if anim_name and anim_name in self.anim_dict:

            anim = self.anim_dict[anim_name]['animation']
            anim_fps = self.anim_dict[anim_name]['fps']

            target_fps = anim_fps / scene_fps

            if len(anim) > 2:  # Don't advance if there's only one cell to the animation

                if target_fps != 0.0:
                    self.subimage += round(target_fps, 2) * freq

            subi = round(self.subimage, 4)

            if (self.subimage <= len(anim) - 2 and anim_fps > 0) or (self.subimage > 1.0 and anim_fps < 0):
                self.is_playing = True

            if self.anim_dict[anim_name]['loop']:  # The animation is to be looped

                fin = 0

                if len(anim) >= 2:

                    while math.floor(subi) > len(anim) - 1:
                        subi -= len(anim) - 1
                        fin = 1

                    while math.floor(subi) < 1.0:
                        subi += len(anim) - 1
                        fin = 1

                if fin:
                    self.on_animation_finished(self)  # Animation's finished because it's looping

                self.is_playing = True

            else:  # No loop

                if subi >= len(anim) - 1 or subi < 1.0:

                    if self.is_playing:
                        self.on_animation_finished(self)  # Animation's finished because it's at the end of a
                        # non-looping animation

                    if len(anim) >= 2:
                        subi = min(max(subi, 1.0), len(anim) - 1)
                    else:
                        subi = 1.0

                    self.is_playing = False

            if math.floor(subi) != math.floor(self.prev_subimage):
                self.on_subimage_change(self, math.floor(subi), math.floor(self.prev_subimage))
                # Callback for subimage change

            self.subimage = subi

        else:

            print("ERROR: ANIMATION NAME " + anim_name + " NOT IN SPRITEMAP OR NOT STRING.")

        self.prev_animation = self.current_animation
        self.prev_subimage = self.subimage

        if self.obj.invalid:  # You did something that killed the object; STOP PRODUCTION!

            print("ERROR: SPRITE MAP OPERATING ON NON-EXISTENT OBJECT!!!")

            return False

        return True
示例#17
0
    def update(self):

        # Mouselook
        if self.delay >= 1:
            
            # Get the center of the screen and the current mouse position
            center = Vector(self.screen_center)
            mouse_position = Vector([logic.mouse.position[0] * self.screen_width, logic.mouse.position[1] * self.screen_height])

            x = center.x - mouse_position.x
            y = center.y - mouse_position.y
            
            # Smooth movement
            self.old_x = (self.old_x*self.mouse_smoothing + x*(1.0-self.mouse_smoothing))
            self.old_y = (self.old_y*self.mouse_smoothing + y*(1.0-self.mouse_smoothing))
                
            x = self.old_x* self.mouse_sensitivity
            y = self.old_y* self.mouse_sensitivity
                 
            # set the values
            self.camera.applyRotation([0, 0, x], False)
            self.camera.applyRotation([y, 0, 0], True)
                
            # Center mouse in game window
            render.setMousePosition(*self.screen_center)
            
        if self.delay <= 1:
            self.delay += 1
        
        
        # Keyboard movement
        keyboard = logic.keyboard.events
        
        if logic.getAverageFrameRate() != 0:
            frame_equaliser = 60 / logic.getAverageFrameRate()
        else:
            frame_equaliser == 1
        
        speed = self.move_speed * frame_equaliser
        
                
        if keyboard[events.LEFTSHIFTKEY]:
            speed = self.move_speed * 3 * frame_equaliser

        if keyboard[events.LEFTCTRLKEY]:
            speed = self.move_speed / 3 * frame_equaliser
        
        if keyboard[events.WKEY]:
            self.camera.applyMovement([0, 0, -speed], True)

        if keyboard[events.SKEY]:
            self.camera.applyMovement([0, 0, speed], True)
            
        if keyboard[events.AKEY]:
            self.camera.applyMovement([-speed, 0, 0], True)
            
        if keyboard[events.DKEY]:
            self.camera.applyMovement([speed, 0, 0], True)
            
        if keyboard[events.EKEY]:
            self.camera.applyMovement([0, speed, 0], True)
            
        if keyboard[events.QKEY]:
            self.camera.applyMovement([0, -speed, 0], True)
示例#18
0
def get_deltatime():
    dt = clamp(0, 1, (1 / logic.getAverageFrameRate()))
    # dt = (1 / logic.getAverageFrameRate())
    return dt
示例#19
0
    def play(self, anim_name, reset_subimage_on_change=True):

        if not anim_name in self.anim_dict:

            print("ERROR: SpriteMap owner " + self.obj.name +
                  " has no animation named " + anim_name + ".")

            return False

        elif len(self.anim_dict[anim_name]['animation']) < 2:

            print("ERROR: SpriteMap owner " + self.obj.name + "'s animation " +
                  anim_name + " does not contain data "
                  "for at least one frame of "
                  "animation.")

            return False

        self.current_animation = anim_name

        if self.current_animation != self.prev_animation:

            self.on_animation_change(self, self.current_animation,
                                     self.prev_animation)  # Callback

            if reset_subimage_on_change:
                self.subimage = 1.0

        if self.adjust_by_sensor_frequency:
            freq = logic.getCurrentController().sensors[0].frequency + 1
        else:
            freq = 1

        if self.fps_lock:
            scene_fps = logic.getLogicTicRate()
        else:
            scene_fps = logic.getAverageFrameRate()
            if scene_fps == 0.0:
                scene_fps = logic.getLogicTicRate()

        if anim_name and anim_name in self.anim_dict:

            anim = self.anim_dict[anim_name]['animation']
            anim_fps = self.anim_dict[anim_name]['fps']

            target_fps = anim_fps / scene_fps

            if len(
                    anim
            ) > 2:  # Don't advance if there's only one cell to the animation

                if target_fps != 0.0:
                    self.subimage += round(target_fps, 2) * freq

            subi = round(self.subimage, 4)

            if (self.subimage <= len(anim) - 2
                    and anim_fps > 0) or (self.subimage > 1.0
                                          and anim_fps < 0):
                self.is_playing = True

            if self.anim_dict[anim_name][
                    'loop']:  # The animation is to be looped

                fin = 0

                if len(anim) >= 2:

                    while math.floor(subi) > len(anim) - 1:
                        subi -= len(anim) - 1
                        fin = 1

                    while math.floor(subi) < 1.0:
                        subi += len(anim) - 1
                        fin = 1

                if fin:
                    self.on_animation_finished(
                        self)  # Animation's finished because it's looping

                self.is_playing = True

            else:  # No loop

                if subi >= len(anim) - 1 or subi < 1.0:

                    if self.is_playing:
                        self.on_animation_finished(
                            self
                        )  # Animation's finished because it's at the end of a
                        # non-looping animation

                    if len(anim) >= 2:
                        subi = min(max(subi, 1.0), len(anim) - 1)
                    else:
                        subi = 1.0

                    self.is_playing = False

            if math.floor(subi) != math.floor(self.prev_subimage):
                self.on_subimage_change(self, math.floor(subi),
                                        math.floor(self.prev_subimage))
                # Callback for subimage change

            self.subimage = subi

        else:

            print("ERROR: ANIMATION NAME " + anim_name +
                  " NOT IN SPRITEMAP OR NOT STRING.")

        self.prev_animation = self.current_animation
        self.prev_subimage = self.subimage

        if self.obj.invalid:  # You did something that killed the object; STOP PRODUCTION!

            print("ERROR: SPRITE MAP OPERATING ON NON-EXISTENT OBJECT!!!")

            return False

        return True
示例#20
0
radioSettings = logic.globalDict['profiles'][profileIndex]['radioSettings']
g = {**droneSettings, **radioSettings} #merge the two dictionaries
scene = logic.getCurrentScene()
mass = own.mass
gravity = 98*mass
camera = scene.objects['cameraMain']
game = scene.objects['Game']

try:
    logic.lastLogicTic
except:
    logic.lastLogicTic = float(time.perf_counter())
    print("creating time")
eTime = float(time.perf_counter())-logic.lastLogicTic
logic.lastLogicTic = float(time.perf_counter())
if(logic.getAverageFrameRate()!=0):
    dm = eTime*60
else:
    dm = 1
if(dm>1):
    dm = 1
def getAngularAcceleration():
    av = own.getAngularVelocity(True)

    if "init" in own:
        lastAv = own['lastAngularVel']
        own['angularAcc'] = getArrayProduct([av[0]-lastAv[0],av[1]-lastAv[1],av[2]-lastAv[2]])
        own['lastAngularVel'] = own.getAngularVelocity(True)

def initAllThings():
    logic.player = own