def test_cross_product(self):

        other = (1,1,1)
        cross, angle = VectorMath.cross_product(self.z,other)
        numpy.testing.assert_allclose([-math.sqrt(3)/3,math.sqrt(3)/3,0.0], cross, atol = 1e-07)
        numpy.testing.assert_allclose ([math.asin(math.sqrt(2.0/3))],[angle], atol = 1e-07)
        bad_vec = (0,0,0,1)
        #print 'This should say vector A is bad:'
        cross,angle = VectorMath.cross_product(bad_vec,self.z)
        #this bad vector argument should fail and return none for both values
        self.assertIsNone(cross)
        self.assertIsNone(angle)
        #print 'This should say vector B is bad:'
        cross,angle = VectorMath.cross_product(self.z,bad_vec)
        #this bad vector argument should fail and return none for both values        
        self.assertIsNone(cross)
        self.assertIsNone(angle)

        simple_x = (1,0)
        simple_y = (0,1)
        cross,angle = VectorMath.cross_product(simple_x,self.y)
        numpy.testing.assert_allclose(self.z,cross)
        numpy.testing.assert_allclose([math.pi/2],angle, atol = 1e-07)

        cross,angle = VectorMath.cross_product(self.z,simple_y)
        numpy.testing.assert_allclose([-1,0,0],cross)
        numpy.testing.assert_allclose([math.pi/2],angle, atol = 1e-07)
 def test_decompose_vector(self):
     mybasis = [self.x,self.y,self.z]
     myvector = (1,2,3)
     assert VectorMath.decompose_vector(myvector,mybasis) == [1,2,3]
     another_basis = [[1,2,3],[0,0,0],[0,0,0]]
     result = VectorMath.decompose_vector(myvector,another_basis)
     self.assertEquals(result,[14,0,0])
 def test_orthagonal(self):
     
     x_prime = (-1,0,0)
     y_close = (0,-.9999999,0.00000000002)
     self.assertFalse (VectorMath.check_orthagonal(self.x,self.x) )
     self.assertFalse (VectorMath.check_orthagonal(self.x,x_prime) )
     self.assertTrue (VectorMath.check_orthagonal(self.x,y_close) )
Example #4
0
 def updateAngle(self, masterOrSlave):
     if not masterOrSlave == self.state:
         return
     
     if self.state:
         if self.target:
             self.setAngle(self.angleToTarget(self.installation.getTarget(self.target)))
         elif self.tertiaryTarget:
             distance = self.targetXDistance(self.tertiaryTarget)
             maxAngle = abs(self.angleToTarget( [ float(self.range[1]),0, 1200 ] ))
             if distance > 0:
                 relevantRange = self.range[1]
                 outOfRange = distance - (int(relevantRange) - int(self.phyLocation[0]))
                 self.setAngle(vm.mapToDomain(outOfRange, 0, float(abs(relevantRange-float(self.extRangeX[1]))), maxAngle, 0))
             elif distance < 0:
                 relevantRange = self.range[0]
                 outOfRange = int(self.phyLocation[0]) - int(relevantRange) + distance
                 self.setAngle( vm.mapToDomain(outOfRange, 0, -1 * float(abs(relevantRange-float(self.extRangeX[0]))), -1 * float(maxAngle), 0) )
             else:
                 raise Exception("Evil's afoot!")
             
             
     elif not self.state:
         i = 0
         comComb = 0
         for command in self.commands:
             comComb += command
             i += 1
         if i == 0:
             self.setAngle(0)
         else:
             self.setAngle(comComb/i)
Example #5
0
 def angleToTarget(self, target):
     target3D = target
     target2D = (int(target3D[0]), int(target3D[2]))
     location2D = (int(self.phyLocation[0]), int(self.phyLocation[2]))
     
     targetVector = vm.createVector(location2D, target2D)
     
     targetAngle = vm.angleBetween2D([0,-1], targetVector)
     return targetAngle
Example #6
0
	def generateProjectile(self, pos):
		shotLifeLength = 200
		shotSpeed = 1
		attack = Attack.Attack("shot.png", self.game, pos, (4,4))
		attack.damage = 5
		attack.velocity = VectorMath.normalize(VectorMath.sub
				(self.game.player.getMidPos(),self.getMidPos()),shotSpeed)
		attack.framesToLive = shotLifeLength
		return attack
    def test_basis_generation(self):
        expected_basis = [[0.0,0.0,-1.0],[0.0,1.0,0.0],[1.0,0.0,0.0]]
        gen_basis = VectorMath.generate_basis(self.x)
        for index,vector in enumerate(expected_basis):
            numpy.testing.assert_allclose(gen_basis[index],vector, atol = 1e-07)

        gen_basis2 = VectorMath.generate_basis((1,1,0))
        expected_basis2 = [[0.5,-0.5,-0.707106781],[-.5,0.5,-0.707106781],[0.707106781,0.707106781,0.0]]
        for index,vector in enumerate(expected_basis2):
            numpy.testing.assert_allclose(gen_basis2[index],vector, atol = 1e-07)
    def nn_multi_base_context(self, targets, n=5):
        """
        Find and return the n nearest base neighbours to a set of target vectors
        from the context matrix.

        :rtype : 2-tuple of ndarrays
        :param target: int
        :param n: int
        """
        d = np.ones(self.size, dtype=np.float)

        new_target = self.base_vectors[targets].sum(axis=0)

        for i, vector in enumerate(self.context_vectors):
            compare = True

            for index in targets:
                if i == index:
                    compare = False

            if compare:
                d[i] = VectorMath.cosine(new_target, vector)

        args = np.argsort(d)[1:n + 1]

        vals = d[args]

        return args, vals
Example #9
0
	def act(self, level):
		SPEED = 1

		oldPos = self.pos
		if(self.facing == FACE_LEFT):
			self.pos = VectorMath.add(self.pos, (-SPEED, 0))
		else:
			self.pos = VectorMath.add(self.pos, (SPEED, 0))

		if(self.isInAir(level)):
			self.pos = oldPos
			self.flipFacing()

		self.pos = VectorMath.add(self.pos, self.velocity)

		if(self.hurtTimer > 0): self.hurtTimer -= 1
Example #10
0
	def attack(self):
		if(self.shotCoolDown == 0):
			distance = self.distanceToPoint(self.game.player.getMidPos())
			shotInitPos = VectorMath.add(self.pos, (6,3))
			self.game.simpleSprites.append(self.generateProjectile(shotInitPos))
			self.shotCoolDown = SHOTCOOLDOWN
			Globals.SOUNDPLAYER.playSound("shoot.wav")
		if(self.shotCoolDown >= 1):
			self.shotCoolDown -=1
Example #11
0
 def determineClosestTarget(self, targetList):
     """
     targetList is a dictionary of targets k = targetID v = point
     returns ID/key of closest Point
     """
     distances = {}
     for key in targetList.keys():
         distances[key] = vm.getPointDistance(self.phyLocation, targetList[key])
     
     return min(distances, key=distances.get)
Example #12
0
 def updateAngle(self, masterOrSlave):
     if not masterOrSlave == self.state:
         return
     
     if self.state:
         if self.target:
             self.setAngle(self.angleToTarget(self.installation.getTarget(self.target)))
         elif self.secondaryTarget:
             distance = self.targetXDistance(self.secondaryTarget)
             #if self.arrLocation[0] == '0' and self.arrLocation[1] == '4':
             #print distance
             #print "distance " + str(distance)
             #maxAngle = abs(self.angleToTarget( [ float(self.range[1])-float(self.phyLocation[0]),0, 1200 ] ))
             maxAngle = abs(self.angleToTarget( [ float(self.range[1]),0, 1200 ] ))
             #print "maxAngle = " + str(vm.radToDeg(maxAngle))
             if distance > 0:
                 relevantRange = self.range[1]
                 outOfRange = distance - (int(relevantRange) - int(self.phyLocation[0]))
                 #print outOfRange
                 #print vm.mapToDomain(outOfRange, 0, float(abs(relevantRange-float(self.phyLocation[0]))), maxAngle, 0)
                 self.setAngle(vm.mapToDomain(outOfRange, 0, float(abs(relevantRange-float(self.phyLocation[0]))), maxAngle, 0))
             elif distance < 0:
                 relevantRange = self.range[0]
                 outOfRange = int(self.phyLocation[0]) - int(relevantRange) + distance
                 #print "oor " + str(outOfRange)
                 #print "reR ", relevantRange
                 #print self.phyLocation
                 self.setAngle( vm.mapToDomain(outOfRange, 0, -1 * float(abs(relevantRange-float(self.phyLocation[0]))), -1 * float(maxAngle), 0) )
             else:
                 raise Exception("Evil's afoot!")
             
             
     elif not self.state:
         i = 0
         comComb = 0
         for command in self.commands:
             comComb += command
             i += 1
         if i == 0:
             self.setAngle(0)
         else:
             self.setAngle(comComb/i)
Example #13
0
 def update(self):
     if not self.lastHurtBox is None:
         if self.lastHurtBox.numberOfHurtFrames > 0:
             self.toBeRemoved = True
             return
     self.tick()
     self.pos = VectorMath.add(self.pos, self.velocity)
     box = pygame.Rect(self.pos, self.frameSize)
     hurtBox = HurtBox.HurtBox(box, 2, 1)
     self.game.hurtBoxHandler.addHurtBox(hurtBox, self.alignment)
     self.lastHurtBox = hurtBox
Example #14
0
    def IncreaseAlpha(self):
        self.Soul.SpriteParticleSystem.Tint *= VectorMath.Vec4(1, 1, 1, 0.9)

        color = self.Owner.Sprite.Color
        color.w += self.IncreaseAlphaDelta
        if (color.w >= 1.0):
            color.w = 1.0
            self.CurrentUpdate = None
            self.DeathActive = True
            self.Soul.Destroy()

        self.Owner.Sprite.Color = color
Example #15
0
class CanBlow:
    BlowDirection = Property.Vector3(VectorMath.Vec3(0, 1, 0))
    BlowForce = Property.Float(4)

    def Initialize(self, initializer):
        pass

    def Blow(self, target, decay):
        if target.RigidBody:
            if VectorMath.Vec3.dot(target.RigidBody.Velocity,
                                   self.BlowDirection) < 4:
                target.RigidBody.ApplyForce(self.BlowDirection *
                                            self.BlowForce * decay)
Example #16
0
    def OnTrigger(self, TriggerEvent):

        if self.Owner.FadeAnim:
            self.Owner.FadeAnim.Active = True

        if self.Owner.Sprite:
            s = self.Owner.Sprite.Color
            self.Owner.Sprite.Color = VectorMath.Vec4(s.x, s.y, s.z, s.a * 0)

        if self.Owner.Collider:
            self.Owner.Collider.Ghost = True
        if self.Owner.Hierarchy:
            for child in self.Owner.Hierarchy.Children:
                if child.Sprite.Color:
                    s = child.Sprite.Color
                    child.Sprite.Color = VectorMath.Vec4(
                        s.x, s.y, s.z, s.a * 0)
                    if child.Collider:
                        child.Collider.Ghost = True

        if self.Owner.IsSentry:
            self.Owner.RemoveComponentByName("IsSentry")
Example #17
0
 def OnLogicUpdate(self, UpdateEvent):
     if self.Active:
         if self.blink_tick <= self.BlinkTick:
             self.blink_tick += 1
         if self.blink_tick >= self.BlinkTick:
             if not self.Owner.Sprite.Color == self.BlinkColor:
                 self.Owner.Sprite.Color = self.BlinkColor
             else:
                 self.Owner.Sprite.Color = self.oricolor
             self.blink_tick = 0
     else:
         c = self.Owner.Sprite.Color
         self.Owner.Sprite.Color = VectorMath.Vec4(self.oricolor.x,self.oricolor.y,self.oricolor.z,c.a)
Example #18
0
    def HideDestroy(self, target):
        target.Sprite.Visible = False

        if target.AIMovementInterface:
            target.AIMovementInterface.Deactivate()

        target.Transform.Translation = VectorMath.Vec3(0, 0, -100)
        target.Collider.Ghost = True

        if not target.RigidBody.Static and not target.RigidBody.Kinematic:
            target.RigidBody.Static = True
        if target.HealthStatus:
            target.HealthStatus.ResetHealth()
    def leftMbRelease(coords=(0, 0)):
        ClickHandler.mouse_release_coords = coords
        ClickHandler.mouse_is_down = False

        # select group of nodes if you made a selection box big enough to not be an accident or single click
        if VectorMath.distance(ClickHandler.mouse_press_coords,
                               ClickHandler.mouse_release_coords) > 10:
            UIGraph.GraphRenderer.selectNodes(
                ClickHandler.mouse_press_coords,
                ClickHandler.mouse_release_coords)
        else:
            # if single click, check for buttons
            for button in UIButton.UIButton.buttons:
                button.checkClicked(ClickHandler.mouse_release_coords)
 def onMouseUpdate(self, ViewportMouseEvent):
     if (self.clicked):
         if (ViewportMouseEvent.ToWorldZPlane(0).x >= self.x_right):
             self.Owner.Transform.Translation = VectorMath.Vec3(
                 self.x_right, self.yvalue, -1)
             self.percent = 100 * (self.Owner.Transform.Translation.x -
                                   self.x_left) / self.total
             self.volume.SpriteText.Text = "Volume: " + str(
                 round(self.percent)) + "%"
         elif (ViewportMouseEvent.ToWorldZPlane(0).x <= self.x_left):
             self.Owner.Transform.Translation = VectorMath.Vec3(
                 self.x_left, self.yvalue, -1)
             self.percent = 100 * (self.Owner.Transform.Translation.x -
                                   self.x_left) / self.total
             self.volume.SpriteText.Text = "Volume: " + str(
                 round(self.percent)) + "%"
         else:
             self.Owner.Transform.Translation = VectorMath.Vec3(
                 ViewportMouseEvent.ToWorldZPlane(0).x, self.yvalue, -1)
             self.percent = 100 * (self.Owner.Transform.Translation.x -
                                   self.x_left) / self.total
             self.volume.SpriteText.Text = "Volume: " + str(
                 round(self.percent)) + "%"
Example #21
0
 def OnLogicUpdate(self, UpdateEvent):
     self.EnsureSetting()
     
     if not self.LevelName == self.parentspace.CurrentLevel.Name:
         self.EnsureAbility()
         
     if self.now_ability != self.GetName():
         c = self.Owner.Sprite.Color
         self.Owner.Sprite.Color *= Vec4(1,1,1,0.9)
         if self.Owner.Sprite.Color.a <= 0.01:
             self.Owner.Sprite.SpriteSource = self.PicTable.FindValue(self.GetName())
             self.now_ability = self.GetName()
     else:
         c = self.Owner.Sprite.Color
         self.Owner.Sprite.Color = VectorMath.Vec4(c.x, c.y, c.z, c.a * 0.9 + 0.1)
Example #22
0
    def Perform(self, position, pre_rotate=None):
        if self.TreeSkill:
            tree = self.TreeSkill.Perform(position, self.PhysSkill)

            if pre_rotate:
                tree.Transform.RotateByAngles(
                    VectorMath.Vec3(0, 0,
                                    pre_rotate.angleZ() - math.pi / 2))
            if tree.Name == "Mushroom":
                tree.CanBounce.ToDirection(pre_rotate)

        elif self.PhysSkill:
            self.PhysSkill.Perform(position)
        else:
            pass
Example #23
0
    def IncreaseAlpha(self):
        self.Soul.SpriteParticleSystem.Tint *= VectorMath.Vec4(1, 1, 1, 0.9)

        color = self.Owner.Sprite.Color
        color.w += self.IncreaseAlphaDelta
        if (color.w >= 1.0):
            color.w = 1.0
            self.CurrentUpdate = None
            self.DeathActive = True
            self.Soul.Destroy()
            if self.Owner.PlayerController.Mouse:
                self.Owner.PlayerController.Mouse.MouseLocationIndicator.Deactivated = False
            self.IsImmune = False

        self.Owner.Sprite.Color = color
 def Initialize(self, initializer):
     #Setting up Update Event
     Zero.Connect(self.Space, Events.LogicUpdate, self.OnLogicUpdate)
     
     #Creating a variable for camera object
     cameraCog = self.Space.FindObjectByName("Camera")
     
     #Setting up Mouse Related Events
     Zero.Connect(cameraCog.Camera.Viewport, Events.MouseMove, self.OnMouseMove)
     Zero.Connect(cameraCog.Camera.Viewport, Events.MouseUpdate, self.OnMouseUpdate)
     
     #Setting mouse position to an x,y,z vector
     self.mousePosition = VectorMath.Vec3(0,0,0)
     
     #making Windows cursor invisible
     Zero.Mouse.Cursor = -1
Example #25
0
class Checkable:
    DarkenedColor = Property.Vector4(VectorMath.Vec4(0.5, 0.5, 0.5, 1))

    def Initialize(self, initializer):
        self.CheckOut()
        Zero.Connect(self.Owner, Events.CollisionStarted, self.OnCollision)

    def OnCollision(self, CollisionEvent):
        if CollisionEvent.OtherObject.CanCheck and not self.activated:
            self.activated = True
            CollisionEvent.OtherObject.CanCheck.SetCheck(self.Owner)
            self.Owner.Sprite.Color = VectorMath.Vec4(1, 1, 1, 1)

    def CheckOut(self):
        self.activated = False
        self.Owner.Sprite.Color = self.DarkenedColor
Example #26
0
    def Perform(self, position):
        ice = self.Space.CreateAtPosition("IceParticle",
                                          self.mouse.Transform.Translation)
        ice.AddComponentByName("ActionList")
        ice.Transform.Translation += VectorMath.Vector3(0, 0, 1)

        def shrink(self):
            self.Owner.SpriteParticleSystem.Tint -= VectorMath.Vec4(
                0, 0, 0, 0.01)
            if self.Owner.SpriteParticleSystem.Tint.a < 0.01:
                self.Owner.Destroy()

        ice.ActionList.AddCallback(callback=shrink,
                                   has_self=True,
                                   blocking=True,
                                   countdown=None)
    def __init__(self,CENTER = (0,0,0),WIDTH = 0,HEIGHT = 0,DEPTH = 0,\
    			 NORMAL = (0,1,0)):
        
        '''These values are in Leap coordinates'''
        self.center = CENTER 
        self.normal_direction = NORMAL # keep this as a tuple, this should not be changing

        '''These values are in local coordinates'''
        self.width = WIDTH
        self.height = HEIGHT
        self.depth = DEPTH
        # when we initialize we set up local coordinates
        self.local_basis = VectorMath.generate_basis(self.normal_direction)


        '''These are values that have nothing to do with reference frame'''
        self.gain_object = Gain()
Example #28
0
 def OnCollision(self, CollisionEvent):
     if not self.hooked and CollisionEvent.OtherObject.Hookable and CollisionEvent.OtherObject.Hookable.Active:
         
         self.hookobject = CollisionEvent.OtherObject
         self.hookobject.Hookable.Hook(self.Owner)
         
         self.Owner.AddComponentByName("GravityEffect")
         self.Owner.GravityEffect.Strength = 5
         self.Owner.GravityEffect.Direction = VectorMath.Vec3(0,-1,0)
         
         self.Owner.AddComponentByName("DragEffect")
         if not self.Owner.Blowable:
             self.Owner.AddComponentByName("Blowable")
         
         self.Owner.PlayerController.JumpActive = False
         
         self.hooked = True
Example #29
0
    def OnCollision(self, CollisionEvent):
        if CollisionEvent.OtherObject.GrowableGround:

            self.normal = -CollisionEvent.FirstPoint.WorldNormalTowardsOther
            self.normal.z = 0
            self.Owner.Transform.Translation += self.normal * CollisionEvent.FirstPoint.Penetration
            if self.ShouldRoot:
                self.Owner.Transform.RotateByAngles(
                    VectorMath.Vec3(0, 0,
                                    self.normal.angleZ() - math.pi / 2))
                CollisionEvent.OtherObject.Transform.Rotation
                self.Owner.RigidBody.Kinematic = True

            if self.Owner.CanBounce:
                self.Owner.CanBounce.ToDirection(self.normal)

            Zero.Disconnect(self.Owner, Events.CollisionStarted, self)
def get_circular_graph_coords(x, y, node_keys, radius):
    # Calculates coordinates in a circle
    # returns dictionary containing node keys to coordinates
    return_dict = dict()  # returns coordinates for each node

    assert len(node_keys) > 0
    deg_current = 0
    deg_increment = float(360 / len(node_keys))

    for circle in node_keys:
        coords = VectorMath.polar_to_cartesian(deg_current, radius)
        coords[0] += x
        coords[1] += y
        return_dict[circle] = coords
        deg_current += deg_increment

    return return_dict
Example #31
0
    def OnLogicUpdate(self, UpdateEvent):
        if self.Active:
            # Update age and do out of bounds check
            self.age += UpdateEvent.Dt * self.direction / self.Duration
            if self.age > 1:
                self.age = 1
                self.Active = False
                if self.Repeat:
                    self.ReversePlay()
            elif self.age < 0:
                self.age = 0
                self.Active = False
                if self.Repeat:
                    self.ReversePlay()

            # set new transform

            self.Owner.Transform.Translation += VectorMath.Vec3(0, 1, 0)
    def OnLogicUpdate(self, UpdateEvent):
        self.UpdateEnvironmentInfo()
        if self.Active and self.WithInRange:
            self.PerformAbsorb()

        target_color = VectorMath.Vec4(1, 1, 1, 0.25)
        target_scale = 2
        target_sprite = self.ShadeTable.FindValue("Circle")
        radius = 1.2
        self.Owner.Transform.Rotation = self.init_rotate

        skillname = self.hero.AbilityStatus.GetTreeSkillName()
        physskill = self.hero.AbilityStatus.GetPhysSkillName()
        if physskill:
            self.Owner.BurnAnim.Active = False
            self.Owner.FreezeAnim.Active = False
            self.Owner.PoisonAnim.Active = False

        if self.WithInRange and not self.Deactivated:
            if self.TouchAttackable:
                target_color = VectorMath.Vec4(1, 0, 0, 0.25)
                target_scale = 5
                radius = 2.4
            elif self.TouchAnnihilator or not skillname:
                target_color = VectorMath.Vec4(0, 0, 0, 1)
                target_scale = 0.5
            elif self.TouchGrowable and not self.hero.AbilityStatus.NoTreeSkill(
            ):
                target_color = VectorMath.Vec4(1, 1, 1, 0.75)
                target_scale = 5
                target_sprite = self.ShadeTable.FindValue(skillname)
                target_scale *= self.scale_table[skillname]

                if not skillname == "TreeSkillWhirlingnut":
                    self.Owner.Transform.RotateByAngles(
                        VectorMath.Vec3(
                            0, 0,
                            self.touch_normal.angleZ() - math.pi / 2))

                if physskill:
                    target_color = self.color_table[physskill]
                    self.anim_table[physskill].Active = True

        else:
            target_color = VectorMath.Vec4(0, 0, 0, 1)
            target_scale = 0.5

        self.Owner.SphereCollider.Radius = radius
        self.Owner.Sprite.Color = target_color
        self.Owner.Transform.Scale = self.initial_size * target_scale
        self.Owner.SphereCollider.Radius = self.ball_size / target_scale
        self.Owner.Sprite.SpriteSource = target_sprite
Example #33
0
    def Initialize(self, initializer):

        self.HUDSpace = Zero.Game.FindSpaceByName("HUDSpace")
        if not self.HUDSpace:
            self.HUDSpace = Zero.Game.CreateNamedSpace("HUDSpace", "Space")
            self.HUDSpace.LoadLevel(self.HUDLevel)

        self.HUDManager = self.HUDSpace.FindObjectByName(
            "LevelSettings").HUDManager
        self.HUDManager.SetParentSpace(self.Space)
        self.HUDManager.ShowBoxes()

        self.HUDManager.HideScores()
        found = self.AbilityOverrideTable.FindValue(
            self.Space.CurrentLevel.Name)
        if found:
            override_time = float(found)
            player = self.Space.FindObjectByName("Player")
            player.AbilityStatus.PlantTimeOverride = override_time

        if self.Space.CurrentLevel.Name[0:3] == "Hub":
            self.HUDManager.ResetScores()

        Zero.Connect(self.Space, Events.LogicUpdate, self.OnLogicUpdate)

        self.HUDManager.UpdateMax()

        self.HUDManager.PlayMusicFor(self.Space.CurrentLevel.Name)
        #elif self.Space.CurrentLevel.Name == "Level3":
        #    self.Space.SoundSpace.PlayMusic("Cave")
        #    self.sequence = Action.Sequence(self.Owner.Actions)
        #    self.PlayAmbient()
        #elif self.Space.CurrentLevel.Name == "Level4" or self.Space.CurrentLevel.Name == "Level5":
        #    self.Space.SoundSpace.PlayMusic("SwampLoop")

        self.player = self.Space.FindObjectByName("Player")
        self.camera = self.Space.FindObjectByName("Camera")
        self.CurrentUpdate = self.UpdateCamera

        pt = self.player.Transform.WorldTranslation
        ct = self.camera.Transform.WorldTranslation
        self.camera.Transform.WorldTranslation = VectorMath.Vec3(
            pt.x, pt.y + 2.5, ct.z)
Example #34
0
 def OnCollision(self, CollisionEvent):
     if not self.hooked and CollisionEvent.OtherObject.Hookable and CollisionEvent.OtherObject.Hookable.Active:
         #if not self.Owner.PlayerController.IsOnGround() and Zero.Keyboard.KeyIsDown(Zero.Keys.W):
         if Zero.Keyboard.KeyIsDown(Zero.Keys.W) or Zero.Keyboard.KeyIsPressed(Zero.Keys.W):
             self.hookobject = CollisionEvent.OtherObject
             self.hookobject.Hookable.Hook(self.Owner)
             
             self.Owner.AddComponentByName("GravityEffect")
             self.Owner.GravityEffect.Strength = 5
             self.Owner.GravityEffect.Direction = VectorMath.Vec3(0,-1,0)
             
             self.Owner.AddComponentByName("DragEffect")
             if not self.Owner.Blowable:
                 self.Owner.AddComponentByName("Blowable")
             
             self.Owner.PlayerController.JumpActive = False
             self.Owner.PlayerGravityModifier.Active = False
             
             self.hooked = True
Example #35
0
    def nn_base_base(self, target, n=5):
        """
        Find and return the n nearest base neighbours to a target vector from
        the base matrix.

        :rtype : 2-tuple of ndarrays
        :param target: int
        :param n: int
        """
        d = np.zeros(self.size, dtype=np.float)

        for i, vector in enumerate(self.base_vectors):
            d[i] = VectorMath.cosine(self.base_vectors[target], vector)

        args = np.argsort(d)[1:n + 1]

        vals = d[args]

        return args, vals
    def GoUnder(self):
        self.Owner.Teleportable.Active = False
        self.Owner.Bounceable.Active = False
        self.Owner.Collider.Ghost = True

        if not self.Owner.Sprite.SpriteSource == self.inanim:
            self.Owner.Sprite.SpriteSource = self.inanim
        if self.Owner.Sprite.CurrentFrame == 2:
            self.dumbcounter = 50
            self.CurrentUpdate = self.UndergroundWalking

            sandsmoke = self.Space.CreateAtPosition(
                "SandSmokeParticle", self.Owner.Transform.Translation)
            t = sandsmoke.SpriteParticleSystem.Tint
            sandsmoke.SpriteParticleSystem.Tint = VectorMath.Vec4(
                t.x, t.y, t.z, 0.1)
            sandsmoke.SphericalParticleEmitter.RandomVelocity *= .5
            sandsmoke.SphericalParticleEmitter.StartVelocity *= .5
            sandsmoke.SphericalParticleEmitter.EmitCount = 10
            sandsmoke.SphericalParticleEmitter.ResetCount()
class PlayerDetectorInterface:
    Size = Property.Vector3(VectorMath.Vec3(1, 1, 1))

    def Initialize(self, initializer):
        self.playerdetector = None

    def Activate(self):
        if not self.playerdetector:
            self.playerdetector = self.Space.CreateAtPosition(
                "PlayerDetectorEntity", self.Owner.Transform.Translation)
            self.SyncSize()
            self.playerdetector.AttachToRelative(self.Owner)

    def Deactivate(self):
        if self.playerdetector:
            self.playerdetector.DetachRelative()
            self.playerdetector.Destroy()

    def SetSize(self, size):
        self.Size = size
        self.SyncSize()

    def SyncSize(self):
        if self.playerdetector:
            self.playerdetector.Transform.Scale = VectorMath.Vec3(
                1, 1, 1) * self.Size

    def GetDirection(self):
        if self.playerdetector:
            return self.playerdetector.PlayerDetector.GetDirection()
        else:
            return VectorMath.Vec3(0, 0, 0)

    def InRange(self):
        if self.playerdetector:
            return self.playerdetector.PlayerDetector.InRange()
        else:
            return False

    def Destroyed(self):
        self.Deactivate()
Example #38
0
 def OnLogicUpdate(self, UpdateEvent):
     
     Parent = self.Owner.Parent
     
     Position = self.Owner.Transform.WorldTranslation
     Child1 = self.Owner.FindChildByName("LookPoint2")
     Child1Pos = Child1.Transform.WorldTranslation
     
     Ray = VectorMath.Ray()
     Ray.Start = Vector3(Position.x, Position.y, 0) #Start
     Ray.Direction = Vector3(Child1Pos.x - Position.x, Child1Pos.y - Position.y, 0) #End
     MaxRayCastDistance = 1.0
     #RayColor = Color.Yellow
     
     CastResultsRange = self.Space.PhysicsSpace.CastRayResults(Ray, 1) # Number Of Objects
     
     LastCastResult = None #Limit
     
     #print(Parent.GunManStatus.CanShoot)
     
     for CastResult in CastResultsRange:
         if(CastResult.Distance >= MaxRayCastDistance):
             break
             
         if(CastResult.ObjectHit.Name == "Tung" or CastResult.ObjectHit.Name == "Austin" or CastResult.ObjectHit.Name == "Trey" or CastResult.ObjectHit.Name == "Peyton" or CastResult.ObjectHit.Name == "Sedrick" or CastResult.ObjectHit.Name == "Julio"):
             Parent.GunManStatus.CanShoot = True
             Parent.GunManStatus.RayCast2 = True
         else:
             Parent.GunManStatus.RayCast2 = False
             
             if(Parent.GunManStatus.RayCast1 is False and Parent.GunManStatus.RayCast2 is False and Parent.GunManStatus.RayCast3 is False and Parent.GunManStatus.RayCast4 is False and Parent.GunManStatus.RayCast5 is False and Parent.GunManStatus.RayCast6 is False and Parent.GunManStatus.RayCast7 is False and Parent.GunManStatus.RayCast8 is False and Parent.GunManStatus.RayCast9 is False):
                 Parent.GunManStatus.CanShoot = False
         
         LastCastResult =  CastResult #Limit
         
     if(not LastCastResult): #Limit
         EndPosition = Ray.Start + Ray.Direction * MaxRayCastDistance
         #self.DrawArrow(Ray.Start, EndPosition, RayColor)
     else:
         EndPosition = Ray.Start + Ray.Direction * LastCastResult.Distance
Example #39
0
 def OnLogicUpdate(self, UpdateEvent):
     #Define target object as the player
     self.targetObject = self.Space.FindObjectByName("Player")
     
     #If the player exists
     if(self.targetObject):
         #Get cameras current translation
         currentTranslation = self.Owner.Transform.Translation
         #Get players's translation
         targetTranslation = self.targetObject.Transform.Translation
         #Store x component of player translation with camera's current y and z translation
         newTranslation = VectorMath.Vec3(targetTranslation.x, currentTranslation.y, currentTranslation.z)
         #set this to cameras translation
         self.Owner.Transform.Translation = newTranslation
         
     #If M is pressed music will be muted
     if(Zero.Keyboard.KeyIsPressed(Zero.Keys.M)):
         #Pauses the Soundspace
         self.Space.SoundSpace.Pause = not self.Space.SoundSpace.Pause
         
     #Sets up the camera for the background so it is slighty off of player movement for effect
     self.Space.FindObjectByName("LevelSettings").HUDCreator.BGSpace.FindObjectByName("Camera").Transform.Translation = VectorMath.Vec3(self.Owner.Transform.Translation.x/2, self.Owner.Transform.Translation.y/2, 40)
    def Attacking(self):
        self.Owner.ClickReceiver.Receivable = True
        

        if not self.Owner.Sprite.SpriteSource == self.outanim:
            self.Owner.Sprite.SpriteSource = self.outanim
            
        if self.Owner.Sprite.CurrentFrame == 2:
            hurtbox = self.Space.CreateAtPosition("HurtBox",self.Owner.Transform.Translation + Vec3(0,.5,0))
            hurtbox.Transform.Scale = Vec3(1,1.5,1)
            hurtbox.CanHurt.HurtRate = -20
            hurtbox.TimedDeath.LifeTime = 0.3
            
            sandsmoke = self.Space.CreateAtPosition("SandSmokeParticle", self.Owner.Transform.Translation)
            t = sandsmoke.SpriteParticleSystem.Tint
            sandsmoke.SpriteParticleSystem.Tint = VectorMath.Vec4(t.x, t.y, t.z, 0.1)
            sandsmoke.SphericalParticleEmitter.EmitCount = 3
            sandsmoke.SphericalParticleEmitter.ResetCount()
            
        if self.Owner.Sprite.CurrentFrame == 5:
            self.dumbcounter = 20
            self.CurrentUpdate = self.Resting
Example #41
0
 def OnLogicUpdate(self, UpdateEvent):
     
     if self.Active:
         if self.Countdown > 0:
             self.Countdown -= 1
         if self.Countdown == 0:
             self.Active = False
             self.Countdown = -1
         
         if self.blink_tick <= self.BlinkTick:
             self.blink_tick += 1
         if self.blink_tick >= self.BlinkTick:
             if not self.Owner.Sprite.Color == self.BlinkColor:
                 self.Owner.Sprite.Color = self.BlinkColor
                 #self.Owner.Sprite.BlendMode = Zero.BlendMode.Additive
               
             else:
                 self.Owner.Sprite.Color = self.oricolor
             self.blink_tick = 0
     else:
         c = self.Owner.Sprite.Color
         self.Owner.Sprite.Color = VectorMath.Vec4(self.oricolor.x,self.oricolor.y,self.oricolor.z,c.a)
Example #42
0
    def Destroy(self):
        if self.InvalidateColliderBox:
            self.Owner.Collider.Offset += VectorMath.Vec3(0, 0, 9999)

        if not self.Activated:
            self.Activated = True
            self.Owner.FadeAnim.Active = True

            def waitmovieend():
                return not self.Owner.FadeAnim.Active

            def destroy():
                self.Owner.Destroy()

            self.Owner.ActionList.AddCallback(callback=waitmovieend,
                                              has_self=False,
                                              blocking=True,
                                              countdown=None)

            self.Owner.ActionList.AddCallback(callback=destroy,
                                              has_self=False,
                                              blocking=True,
                                              countdown=1)
Example #43
0
class BlinkAnim:
    BlinkColor = Property.Color(VectorMath.Vec4(1,0,0,1))
    BlinkTick = Property.Int(3)
    Active = Property.Bool(False)

    def Initialize(self, initializer):
        self.blink_tick = self.BlinkTick
        self.blink_counter = 0
        self.oricolor = self.Owner.Sprite.Color
        Zero.Connect(self.Space, Events.LogicUpdate, self.OnLogicUpdate)
        
    def OnLogicUpdate(self, UpdateEvent):
        if self.Active:
            if self.blink_tick <= self.BlinkTick:
                self.blink_tick += 1
            if self.blink_tick >= self.BlinkTick:
                if not self.Owner.Sprite.Color == self.BlinkColor:
                    self.Owner.Sprite.Color = self.BlinkColor
                else:
                    self.Owner.Sprite.Color = self.oricolor
                self.blink_tick = 0
        else:
            c = self.Owner.Sprite.Color
            self.Owner.Sprite.Color = VectorMath.Vec4(self.oricolor.x,self.oricolor.y,self.oricolor.z,c.a)
Example #44
0
class TouchFlyhere:
    HidingOffset = Property.Float(10)
    Normal = Property.Vector3(VectorMath.Vec3(0, 1, 0))

    def Initialize(self, initializer):
        self.destination = self.Owner.Transform.WorldTranslation
        hiding_vec = self.HidingOffset * self.Owner.Transform.TransformNormalLocal(
            self.Normal)

        self.Owner.Transform.WorldTranslation += hiding_vec
        self.Owner.Collider.Offset -= VectorMath.Vec3(0, self.HidingOffset, 0)
        Zero.Connect(self.Owner, Events.CollisionStarted, self.OnCollision)

    def OnCollision(self, CollisionEvent):
        Zero.Connect(self.Space, Events.LogicUpdate, self.FlyUpdate)
        Zero.Disconnect(self.Owner, Events.CollisionStarted, self)

    def FlyUpdate(self, UpdateEvent):
        t = self.Owner.Transform.WorldTranslation
        self.Owner.Transform.WorldTranslation = t * 0.9 + self.destination * 0.1

        if (self.Owner.Transform.WorldTranslation -
                self.destination).length() < 0.01:
            Zero.Disconnect(self.Space, Events.LogicUpdate, self)
Example #45
0
	def distanceToPoint(self, point):
		return VectorMath.magnitude((VectorMath.sub(self.pos,point)))
 def convert_to_local_coordinates(self,coordinates,basis):
 	# find the relative vector from local origin to leap point
 	relative_vector = [value-self.center[index] for index,value in enumerate(coordinates)]
 	local_coordinates = VectorMath.decompose_vector(relative_vector,basis)
     return local_coordinates
Example #47
0
    stl_regex = re.compile("(\.STL)|(\.stl)$")
    if(re.search(stl_regex, fn) is not None):
        out_name = re.split(stl_regex, fn)[0]
    else:
        print "Exiting: invalid filename is not a .stl or .STL"
        print "\t"+fn
        exit(1)

    #try to create a dir for output
    out_dir = "./out"
    try:
        os.mkdir(out_dir)
    except OSError:
        print "dir already exists"

    magnitude = VectorMath.magnitude(norm_vec)
    norm_vec = tuple([norm_vec[i]/magnitude for i in range(0, len(norm_vec))])

    if norm_vec != (0,0,1):
        #print norm_vec
        #print VectorMath.magnitude(norm_vec)
        (basis, rot_quaternion) = VectorMath.generate_basis(norm_vec)
        mesh = smi.parsers.parseBinarySTL(fn, quaternion = rot_quaternion, scale = global_scale )
    else:
        mesh = smi.parsers.parseBinarySTL(fn)

    print "Min",mesh.min_coord
    print "Max",mesh.max_coord

    all_dwg = ezdxf.new("AC1015")
    all_msp = all_dwg.modelspace()