상속: MonoBehaviour
예제 #1
0
     //private Animator animator;


     public void Start()
     {
          // Components
          moveController = GetComponent<EnemyMoveController>();
          animationController = GetComponent<AnimationController>();
          sprRend = GetComponent<SpriteRenderer>();
          collider = GetComponent<BoxCollider2D>();
          health = GetComponent<Health>();
          player = FindObjectOfType<Player>();

          //laser = GetComponent<Projectile> ();
          //laserObject = GetComponent <Projectile> ();

          //rigidbody2D.mass = 10;

          distance = new Vector2(0, 0);
          speed = new Vector2(0, 0);
          isAgro = false;

          rnd = new System.Random(Guid.NewGuid().GetHashCode());
          t = 3 + rnd.Next(0, 3000) / 1000f;

          teleporting = false;
          teleportCD = 11;
          temp = 0;
          canTeleport = true;

          facing = new Vector2(0, 0);

     }
예제 #2
0
        public RenderObjectUnity(AnimatorEditor editor, HashSet<string> meshNames)
        {
            HighlightSubmesh = new HashSet<int>();
            highlightMaterial = new SlimDX.Direct3D9.Material();
            highlightMaterial.Ambient = new Color4(1, 1, 1, 1);
            highlightMaterial.Diffuse = new Color4(1, 0, 1, 0);

            this.device = Gui.Renderer.Device;
            this.tweeningVertDec = new VertexDeclaration(this.device, TweeningWithoutNormalsVertexBufferFormat.ThreeStreams);

            Textures = new Texture[editor.Textures.Count];
            Materials = new SlimDX.Direct3D9.Material[editor.Materials.Count];

            rootFrame = CreateHierarchy(editor, meshNames, device, out meshFrames);

            AnimationController = new AnimationController(numFrames, 30, 30, 1);
            Frame.RegisterNamedMatrices(rootFrame, AnimationController);

            if (meshFrames.Count > 0)
            {
                Bounds = meshFrames[0].Bounds;
                for (int i = 1; i < meshFrames.Count; i++)
                {
                    Bounds = BoundingBox.Merge(Bounds, meshFrames[i].Bounds);
                }
            }
            else
            {
                Bounds = new BoundingBox();
            }
        }
예제 #3
0
        public void Test_New()
        {
            var anim = new AnimationController ();

            Assert.AreEqual (0, anim.ClipCount);
            Assert.AreEqual (0, anim.Clips.Count ());
        }
예제 #4
0
        public static Node Create(Vector3 pos)
        {
            var cmp = new MyComponent ();

            var spr = new Sprite (480, 300);
            spr.AddTexture (new Texture ("media/Vanity.jpg"));
            spr.AddTexture (new Texture ("media/Tanks.png"));
            spr.AddTexture (new Texture ("media/TatamiRoom.png"));
            spr.AutoScale = true;

            Console.WriteLine ("tex = " + spr.GetTexture (0));
            Console.WriteLine ("spr = " + spr);

            var col = new CollisionObject();
            col.Shape  = new BoxShape(spr.Width/2, spr.Height/2, 100);
            col.SetOffset (spr.Width/2, spr.Height/2, 0);

            var ctr = new AnimationController ();

            var node = new Node ();
            node.Attach (cmp);
            node.Attach (spr);
            node.Attach (col);
            node.Attach (ctr);

            node.Translation = pos;

            var clip = new SoundClip ("Sound");
            clip.AddTrack (new SoundEffectTrack ("media/PinPon.wav"));

            node.UserData.Add (clip.Name, clip);

            return node;
        }
예제 #5
0
        public RenderObjectREM(remParser parser, remMesh mesh)
        {
            HighlightSubmesh = new HashSet<int>();
            highlightMaterial = new Material();
            highlightMaterial.Ambient = new Color4(1, 1, 1, 1);
            highlightMaterial.Diffuse = new Color4(1, 0, 1, 0);

            this.device = Gui.Renderer.Device;

            if (Textures.Count + parser.MATC.Count > Textures.Capacity)
            {
                Textures.Capacity += parser.MATC.Count;
            }
            Materials = new Material[parser.MATC.Count];

            rootFrame = CreateHierarchy(parser, mesh, device, out meshFrames);

            AnimationController = new AnimationController(numFrames, 30, 30, 1);
            Frame.RegisterNamedMatrices(rootFrame, AnimationController);

            for (int i = 0; i < meshFrames.Count; i++)
            {
                if (i == 0)
                {
                    Bounds = meshFrames[i].Bounds;
                }
                else
                {
                    Bounds = BoundingBox.Merge(Bounds, meshFrames[i].Bounds);
                }
            }
        }
예제 #6
0
        public RenderObjectODF(odfParser parser, HashSet<int> meshIDs)
        {
            HighlightSubmesh = new SortedSet<int>();
            highlightMaterial = new Material();
            highlightMaterial.Ambient = new Color4(1, 1, 1, 1);
            highlightMaterial.Diffuse = new Color4(1, 0, 1, 0);

            this.device = Gui.Renderer.Device;

            Textures = new Texture[parser.TextureSection != null ? parser.TextureSection.Count : 0];
            TextureDic = new Dictionary<int, int>(parser.TextureSection != null ? parser.TextureSection.Count : 0);
            Materials = new Material[parser.MaterialSection.Count];
            BoneMatrixDic = new Dictionary<string, Matrix>();

            rootFrame = CreateHierarchy(parser, meshIDs, device, out meshFrames);

            AnimationController = new AnimationController(numFrames, 30, 30, 1);
            Frame.RegisterNamedMatrices(rootFrame, AnimationController);

            for (int i = 0; i < meshFrames.Count; i++)
            {
                if (i == 0)
                {
                    Bounds = meshFrames[i].Bounds;
                }
                else
                {
                    Bounds = BoundingBox.Merge(Bounds, meshFrames[i].Bounds);
                }
            }
        }
예제 #7
0
          //private Animator animator;


          public void Start()
          {
               //animator = GetComponent<Animator>();

               moveController = GetComponent<EnemyMoveController>();
               animationController = GetComponent<AnimationController>();
               health = GetComponent<Health>();
               player = FindObjectOfType<Player>();

               //rigidbody2D.mass = 10;
               distance = new Vector2(0, 0);
               speed = new Vector2(0, 0);
               isAgro = false;
               attackDelay = 3;

               rnd = new System.Random(Guid.NewGuid().GetHashCode());
               t = 3 + rnd.Next(0, 3000) / 1000f;

               facing = new Vector2(0, 0);
               point = new Vector2(100, 100);
               distanceFromPoint = new Vector2(100, 100);
               up = new Vector2(0, 0.4f);
               left = new Vector2(-0.4f, 0);
               right = new Vector2(0.4f, 0);
               down = new Vector2(0, -0.4f);
               canAttack = true;

          }
예제 #8
0
	// Use this for initialization
	void Start ()
    {
        animationController = transform.GetChild(0).GetComponent<AnimationController>();
        audioManager = GameObject.FindWithTag("AudioManager").GetComponent<AudioManager>();
        StartCoroutine("NewCombo",false);
        SetAi();
        allButtons = gen.AllButtons(player);
	}
예제 #9
0
	void Start()
	{
		motor = GetComponent<PlayerMotor> ();
        joint = GetComponent<ConfigurableJoint>();
        AC = GetComponent<AnimationController>();

        setJointSetting(jointSpring); 
	}
예제 #10
0
	public TurretUndeployingState(GameObject npc, CannonController[] cannonControllers, BodyController baseController, AnimationController animationController): base(npc)
	{
		stateID 					= StateID.UnDeploying;
		turretActor	 				= npc.GetComponent<SuperTurret>();
		this.cannonControllers 		= cannonControllers;
		this.baseController 		= baseController;
		this.animationController 	= animationController;
	}
예제 #11
0
        public void Test_Indexer()
        {
            var anim = new AnimationController ();
            var clip = new AnimationClip (100, "Clip");
            anim.AddClip (clip);

            Assert.AreEqual (clip, anim["Clip"]);
        }
예제 #12
0
 protected override void Dispose(bool disposing)
 {
     if (_controller != null)
     {
         _controller.Dispose();
         _controller = null;
     }
 }
예제 #13
0
 public BaseUnitBehaviour( EntityController.GetTarget getTarget, EntityController.Faction faction, UnitViewPresenter myViewPresenter, AnimationController animationController)
 {
     this.myViewPresenter = myViewPresenter;
     this.animationController = animationController;
     myFaction = faction;
     this.navMeshAgent = myViewPresenter.navMeshAgent;
     GetTargetDelegate = getTarget;
     InitStateMachine();
 }
예제 #14
0
    // Use this for initialization
    void Start()
    {
        _controller = GetComponent<CharacterController>();
        GameObject gameControllerObj = GameObject.FindGameObjectsWithTag( "GameController" )[0];

        _gameController = gameControllerObj.GetComponent(typeof(GameStateController)) as GameStateController;
        _state = State.ALIVE;
        _sprite = animatedPlane.GetComponent(typeof(AnimationController)) as AnimationController;
    }
예제 #15
0
 public void Awake()
 {
     m_GroundLayer 	= 1 << LayerMask.NameToLayer("Ground");
     m_WallLayer 	= 1 << LayerMask.NameToLayer("Wall");
     m_distance 		= 0.0f;
     m_DashDistance 	= 5.0f;
     m_animator 		= GetComponent<AnimationController>();
     m_HeroRigidBody = GetComponent<Rigidbody2D>();
     m_canWallJump 	= true;
 }
	// Use this for initialization
	void Start ()
	{
		animations = new AnimationClip[5];
		animations[0] = null;
		animations[1] = tornado;
		animations[2] = meteor;
		animations[3] = flood;
		animations[4] = ufo;
		current = this;
	}
예제 #17
0
        public static Node Create(Vector3 pos)
        {
            var cmp = new MyFireExplosion ();

               var spr = new Sprite (100, 100);
               spr.AddTexture (new Texture ("media/FireExplosion.png"));

               var track = new AnimationTrack ("TextureOffset", InterpolationType.Step);
               track.AddKeyframe (0, new Vector2 (0, 0));
               track.AddKeyframe (100, new Vector2 (100, 0));
               track.AddKeyframe (200, new Vector2 (200, 0));
               track.AddKeyframe (300, new Vector2 (300, 0));
               track.AddKeyframe (400, new Vector2 (400, 0));
               track.AddKeyframe (500, new Vector2 (500, 0));
               track.AddKeyframe (600, new Vector2 (600, 0));
               track.AddKeyframe (700, new Vector2 (700, 0));
               track.AddKeyframe (800, new Vector2 (800, 0));
               track.AddKeyframe (900, new Vector2 (900, 0));
               track.AddKeyframe (1000, new Vector2 (0, 100));
               track.AddKeyframe (1100, new Vector2 (100, 100));
               track.AddKeyframe (1200, new Vector2 (200, 100));
               track.AddKeyframe (1300, new Vector2 (300, 100));
               track.AddKeyframe (1400, new Vector2 (400, 100));
               track.AddKeyframe (1500, new Vector2 (500, 100));
               track.AddKeyframe (1600, new Vector2 (600, 100));
               track.AddKeyframe (1700, new Vector2 (700, 100));
               track.AddKeyframe (1800, new Vector2 (800, 100));
               track.AddKeyframe (1900, new Vector2 (900, 100));
               track.AddKeyframe (2000, new Vector2 (0, 200));
               track.AddKeyframe (2100, new Vector2 (100, 200));
               track.AddKeyframe (2200, new Vector2 (200, 200));
               track.AddKeyframe (2300, new Vector2 (300, 200));
               track.AddKeyframe (2400, new Vector2 (400, 200));
               track.AddKeyframe (2500, new Vector2 (500, 200));
               track.AddKeyframe (2600, new Vector2 (600, 200));
               track.AddKeyframe (2700, new Vector2 (700, 200));
               track.AddKeyframe (2800, new Vector2 (800, 200));
               track.AddKeyframe (2900, new Vector2 (900, 200));

               var clip = new AnimationClip (3000, "FireExplosion");
               clip.AddTrack (spr, track);
               clip.WrapMode = WrapMode.Loop;

               var anim = new AnimationController ();
               anim.AddClip (clip);

               var node = new Node ();
               node.Attach (cmp);
               node.Attach (spr);
               node.Attach (anim);

               node.Translation = pos;

               return node;
        }
예제 #18
0
	/// <summary>
	/// Start this instance.
	/// </summary>
	void Start ()
	{
		controller = GetComponent<Controller2D>();
		animationController = GetComponent<AnimationController>();

		gravity = -(2 * maxJumpHeight) / Mathf.Pow (timeToJumpApex, 2);
		maxJumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
		minJumpVelocity = Mathf.Sqrt(2 * Mathf.Abs(gravity) * minJumpHeight);

		//print("Gravity: " + gravity + " - Jump Velocity: " + maxJumpHeight);
	}
예제 #19
0
 /// <inheritdoc/>
 protected override void OnInitialize(AnimationManager animationManager)
 {
     // Start fade-out animation on animation weight.
       var fadeOutAnimation = new SingleFromToByAnimation
       {
     To = 0,
     Duration = _fadeOutDuration,
     EasingFunction = DefaultEase,
     FillBehavior = FillBehavior.Stop,
       };
       _fadeOutController = animationManager.StartAnimation(fadeOutAnimation, AnimationInstance.WeightProperty);
 }
예제 #20
0
        /// <inheritdoc/>
        protected override void OnInitialize(AnimationManager animationManager)
        {
            // Start fade-in animation on animation weight.
              var fadeInAnimation = new SingleFromToByAnimation
              {
            From = 0,
            Duration = _fadeInDuration,
            EasingFunction = DefaultEase,
            FillBehavior = FillBehavior.Stop,
              };
              _fadeInController = animationManager.StartAnimation(fadeInAnimation, AnimationInstance.WeightProperty);

              // Add animation.
              animationManager.Add(AnimationInstance, HandoffBehavior.Compose, _previousAnimation);
        }
예제 #21
0
    void Awake()
    {
        mouseOverChest = false;

        gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();

        talentManager = transform.GetComponent<TalentManager>();
        spellBook = new List<Ability>();

        DontDestroyOnLoad(transform.gameObject);

        Instantiate(gameManager.SpawnInParticles, transform.position, Quaternion.identity);
        mouseOverGUI = false;
        _animationController = GetComponent<AnimationController>();
    }
예제 #22
0
          public void Start()
          {
               //animator = GetComponent<Animator>();

               moveController = GetComponent<EnemyMoveController>();
               animationController = GetComponent<AnimationController>();
               health = GetComponent<Health>();
               player = FindObjectOfType<Player>();

               //rigidbody2D.mass = 10;
               distance = new Vector2(0, 0);
               isAgro = false;

               rnd = new System.Random(Guid.NewGuid().GetHashCode());
               t = 3 + rnd.Next(0, 3000) / 1000f;


          }
예제 #23
0
        public void Test_AddClip()
        {
            var anim = new AnimationController ();
            var clip1 = new AnimationClip (100, "Name");
            var clip2 = new AnimationClip (100, "Name");

            anim.AddClip (clip1);
            anim.AddClip (clip2);

            Assert.AreEqual (2, anim.ClipCount);
            Assert.AreEqual (2, anim.Clips.Count ());

            anim.RemoveClip (clip1);
            anim.RemoveClip (clip2);

            Assert.AreEqual (0, anim.ClipCount);
            Assert.AreEqual (0, anim.Clips.Count ());
        }
예제 #24
0
파일: PlayerControl.cs 프로젝트: NoaAka/P6
    void Start () {
		input = GameObject.FindWithTag ("InputControl").GetComponent<InputControl> ();
        god = GameObject.FindWithTag("GameController").GetComponent<God>();

        //playerShip 
        playerShip = GameObject.FindGameObjectWithTag("PlayerShip");

        //shield 
        animationController = GetComponentInChildren<AnimationController>();
        playerShield = GameObject.FindGameObjectWithTag("PlayerShield");
        if (shieldPower > 0f)
        {
            ActivateShield();
        }
        else
        {
            DissactivateShield();
        }
    }
        public ARefillController(Vector2 position, string refillType)
        {
            this.IsActive = true;

            m_position = position;
            m_refillType = refillType;

            m_refillArea = new Rectangle(s_refillArea.X, s_refillArea.Y, s_refillArea.Width, s_refillArea.Height);
            m_refillArea.Offset((int)m_position.X, (int)m_position.Y);

            Rectangle bounds = new Rectangle(-40, -120, 80, 120);
            m_collider = new Collider(this, bounds, ColliderType.Scenery);

            m_animationController =
                new AnimationController(
                    "Animation/Data/MissionObjects",
                    "Animation/Textures/MissionObjects",
                    AnimationName);
        }
예제 #26
0
		protected override void Start()
		{
			base.Start();

			EnableGestureManipulation = true;

			Zone.AmbientColor = new Color(0.8f, 0.8f, 0.8f);
			DirectionalLight.Brightness = 1;

			mutantNode = Scene.CreateChild();
			mutantNode.Position = new Vector3(0, 0, 2f);
			mutantNode.SetScale(0.2f);
			var mutant = mutantNode.CreateComponent<AnimatedModel>();

			mutant.Model = ResourceCache.GetModel("Models/Mutant.mdl");
			mutant.SetMaterial(ResourceCache.GetMaterial("Materials/mutant_M.xml"));
			animation = mutantNode.CreateComponent<AnimationController>();
			PlayAnimation(IdleAni);

			RegisterCortanaCommands(new Dictionary<string, Action>
				{
					//play animations using Cortana
					{"idle", () => PlayAnimation(IdleAni)},
					{"die", () => PlayAnimation(KillAni)},
					{"dance", () => PlayAnimation(HipHopAni)},
					{"jump", () => PlayAnimation(JumpAni)},
					{"jump attack", () => PlayAnimation(JumpAttack)},
					{"kick", () => PlayAnimation(KickAni)},
					{"punch", () => PlayAnimation(PunchAni)},
					{"run", () => PlayAnimation(RunAni)},
					{"swipe", () => PlayAnimation(SwipeAni)},
					{"walk", () => PlayAnimation(WalkAni)},

					{"bigger", () => mutantNode.ScaleNode(1.2f)},
					{"smaller", () => mutantNode.ScaleNode(0.8f)},
					{"increase the brightness", () => IncreaseBrightness(1.2f)},
					{"decrease the brightness", () => IncreaseBrightness(0.8f)},
					{"look at me", LookAtMe },
					{"turn around", () => mutantNode.RunActions(new RotateBy(1f, 0, 180, 0))},
					{"help", Help }
				});
		}
예제 #27
0
        public void OnDeath()
        {
            if (_dead)
                return;

            Object.SearchComponent<Collider>().IsTrigger = true;
            Object.SearchComponent<RigidBody>().Momentum = new SharpDX.Vector3(0, 0, 1);
            Object.SearchComponent<LookForward>().Update(TimeSpan.Zero);
            Object.SearchComponent<RigidBody>().Momentum = SharpDX.Vector3.Zero;

            if (OnDeathStarted != null)
                OnDeathStarted(this, EventArgs.Empty);

            _dead = true;

            Object.Enabled = false;
            _controller = new AnimationController(Object, Delay, JumpForce);
            _controller.OnDeathFinalized += controller_OnDeathFinalized;
            Object.GetAncestor<Scene>().Add(_controller);
            _controller.Init();
        }
    public BaseUnitController(
        EntityController.Select entityControllerSelect, 
        UnitViewPresenter unitViewPresenter, 
        BaseUnit.UnitCharacteristics unitCharacteristics, 
        EntityController.GetTarget getTarget, 
        EntityController.Faction faction, 
        DeathDestroy updateDeath,
        BaraksModel.SetUpdeteCharacteristicsDelegate setUpdeteCharacteristicsDelegate )
    {
        this.updateDeath = updateDeath;

        animationController = new AnimationController( unitViewPresenter._animation );

        EffectsController effectsController = new EffectsController();

        tempNavMeshAgent = unitViewPresenter.navMeshAgent;

        this.entityControllerSelect = entityControllerSelect;
        unitBehaviour = new BaseUnitBehaviour( getTarget, faction, unitViewPresenter, animationController );
        unitModel = new BaseUnit(unitCharacteristics, faction, effectsController, _UpdateCharacteristics, UpdateDeath, setUpdeteCharacteristicsDelegate, DeleteVisualEffect );
        unitView = new BaseUnitView( unitViewPresenter, Selected, GetDamage );
    }
예제 #29
0
        public ChozoStatue(Vector2 position, Item item, Direction facing)
        {
            if (facing != Direction.Left && facing != Direction.Right)
            {
                facing = Direction.Right;
            }

            m_position = position;
            m_item = item;
            m_facing = facing;
            m_statueAnimation = new AnimationController(
                "Animation/Data/MissionObjects",
                "Animation/Textures/MissionObjects",
                StatueAnimation);
            m_itemAnimation = new AnimationController(
                "Animation/Data/MissionObjects",
                "Animation/Textures/MissionObjects",
                ItemAnimation);

            Rectangle bounds;
            if (m_facing == Direction.Left)
            {
                bounds = new Rectangle(
                    (int)m_position.X - 60,
                    (int)m_position.Y - 120,
                    40,
                    40);
            }
            else
            {
                bounds = new Rectangle(
                    (int)m_position.X + 20,
                    (int)m_position.Y - 120,
                    40,
                    40);
            }
            m_collider = new Collider(this, bounds, ColliderType.Scenery);
        }
예제 #30
0
        public void Test_OnAnimate_Event_2()
        {
            var clip = new AnimationClip (100, "TestClip");
            clip.WrapMode = WrapMode.Once;
            clip.Play ();

            var args1 = new MyEventArgs (1);
            var args2 = new MyEventArgs (2);
            var args3 = new MyEventArgs (3);

            var count = 0;
            clip.AddEvent (0, (sender, args) => count = 1, null);
            clip.AddEvent (50, (sender, args) => count = 2, null);
            clip.AddEvent (100, (sender, args) => count += 1, null);
            clip.AddEvent (100, (sender, args) => count += 1, null);

            var anim = new AnimationController ();
            anim.AddClip (clip);

            // 停止中のクリップはイベントを発火しない
            clip.Stop ();
            anim.OnAnimate (0, 0);
            Assert.AreEqual (0, count);

            clip.Play ();

            // 逆再生中の dtime は逆方向
            // clip.SetSpeed (-1, 50);
            // anim.OnAnimate (40, 10);
            // Assert.AreEqual (2, count);

            count = 0;
            clip.Speed = 1;

            // 同じポジションで重複したイベントは両方発火
            anim.OnAnimate (100, 0);
            Assert.AreEqual (2, count);
        }
예제 #31
0
        private void btnAnimate_Click(object sender, EventArgs e)
        {
            if (lstValues.SelectedIndices.Count != 1)
            {
                return;
            }

            using (Form frmAnimate = new Form())
            {
                frmAnimate.Text            = "Animate value";
                frmAnimate.FormBorderStyle = FormBorderStyle.FixedToolWindow;
                frmAnimate.StartPosition   = FormStartPosition.CenterParent;

                Type    controlType = pnlContainer.Controls.Cast <Control>().First().GetType();
                Control ctrlStart   = (Control)Activator.CreateInstance(controlType);
                Control ctrlEnd     = (Control)Activator.CreateInstance(controlType);

                ctrlStart.Location = new Point(0, 0);
                ctrlEnd.Location   = new Point(0, ctrlStart.Height + 10);

                Button btnOk = new Button()
                {
                    Text = "Ok", Width = 32, Height = 23
                };
                btnOk.Location = new Point(frmAnimate.Width - btnOk.Width - 80, ctrlStart.Height + ctrlEnd.Height + 20);

                btnOk.Click += (s, f) =>
                {
                    frmAnimate.DialogResult = DialogResult.OK;
                    frmAnimate.Close();
                };

                frmAnimate.Controls.Add(btnOk);

                frmAnimate.Width  = ctrlStart.Width + 20;
                frmAnimate.Height = ctrlStart.Height + ctrlEnd.Height + 85;

                frmAnimate.Controls.Add(ctrlStart);
                frmAnimate.Controls.Add(ctrlEnd);

                if (frmAnimate.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                if (_animator == null)
                {
                    _animator = new AnimationController(_generator);
                    btnResetAnimations.Visible = true;
                }

                if (ctrlStart is ctrlFloatController)
                {
                    float from = ((ctrlFloatController)ctrlStart).Value;
                    float to   = ((ctrlFloatController)ctrlEnd).Value;
                    _animator.AddAnimation(lstValues.SelectedItems[0].Tag as FieldInfo, from, to);
                    lstValues.SelectedItems[0].SubItems[1].Text = from + " - " + to;
                }
                else if (ctrlStart is ctrlIntController)
                {
                    int from = ((ctrlIntController)ctrlStart).Value;
                    int to   = ((ctrlIntController)ctrlEnd).Value;
                    _animator.AddAnimation(lstValues.SelectedItems[0].Tag as FieldInfo, from, to);
                    lstValues.SelectedItems[0].SubItems[1].Text = from + " - " + to;
                }

                lstValues.SelectedItems[0].ForeColor = Color.Brown;
            }
        }
        protected override void CalculateTransforms(float distance)
        {
            ProfilerShort.Begin("MyCharacter.CalculateTransforms");

            base.CalculateTransforms(distance);
            if (m_headBoneIndex >= 0 && AnimationController.CharacterBones != null && (IsInFirstPersonView || ForceFirstPersonCamera) && ControllerInfo.IsLocallyControlled() && !IsBot)
            {
                Vector3 headHorizontalTranslation = AnimationController.CharacterBones[m_headBoneIndex].AbsoluteTransform.Translation;
                headHorizontalTranslation.Y = 0;
                MyCharacterBone.TranslateAllBones(AnimationController.CharacterBones, -headHorizontalTranslation);
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Calculate Hand IK");


            if (this == MySession.Static.ControlledEntity)
            {
                // (OM) Note: only controlled character can get it's aimed point from camera, otherwise all character's will aim the same direction
                // set the aimed point explicitly using AimedPoint property
                m_aimedPoint = GetAimedPointFromCamera();
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().StartNextBlock("Update anim IK");

            AnimationController.UpdateInverseKinematics(); // since we already have absolute transforms

            VRageRender.MyRenderProxy.GetRenderProfiler().StartNextBlock("UpdateLeftHandItemPosition");
            if (m_leftHandItem != null)
            {
                UpdateLeftHandItemPosition();
            }

            if (m_currentWeapon != null && WeaponPosition != null && m_handItemDefinition != null)
            {
                WeaponPosition.Update();
                //mainly IK and some zoom + ironsight stuff
                if (m_handItemDefinition.SimulateLeftHand && m_leftHandIKStartBone != -1 && m_leftHandIKEndBone != -1)
                {
                    MatrixD leftHand = (MatrixD)m_handItemDefinition.LeftHand * ((MyEntity)m_currentWeapon).WorldMatrix;
                    CalculateHandIK(m_leftHandIKStartBone, m_leftForearmBone, m_leftHandIKEndBone, ref leftHand);
                }

                if (m_handItemDefinition.SimulateRightHand && m_rightHandIKStartBone != -1 && m_rightHandIKEndBone != -1 && IsSitting == false)
                {
                    MatrixD rightHand = (MatrixD)m_handItemDefinition.RightHand * ((MyEntity)m_currentWeapon).WorldMatrix;
                    CalculateHandIK(m_rightHandIKStartBone, m_rightForearmBone, m_rightHandIKEndBone, ref rightHand);
                }
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().StartNextBlock("ComputeBoneTransform");

            var characterBones = AnimationController.CharacterBones;

            if (characterBones == null)
            {
                return;
            }
            for (int i = 0; i < characterBones.Length; i++)
            {
                MyCharacterBone bone = characterBones[i];
                bone.ComputeBoneTransform();
                BoneRelativeTransforms[i] = bone.RelativeTransform;
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            ProfilerShort.End();
        }
예제 #33
0
 private void Awake()
 {
     animcontroller = this.GetComponent <AnimationController>();
     PC             = FindObjectOfType <PlayerCharacter>();
 }
예제 #34
0
 private void Start()
 {
     animController = GetComponent <AnimationController>();
 }
예제 #35
0
 private void Awake()
 {
     animationController = GetComponent <AnimationController>();
     gameplayController  = GetComponent <GameplayController>();
 }
예제 #36
0
 // Use isto para inicialização
 void Start()
 {
     rb = GetComponent <Rigidbody2D>() ?? null;
     pm = GetComponent <PlayerMovement>() ?? null;
     ac = GetComponent <AnimationController>() ?? null;
 }
예제 #37
0
 void Awake()
 {
     animationController = GetComponent<AnimationController>();
 }
예제 #38
0
 // Use this for initialization
 void Awake()
 {
     agent = GetComponent <NavMeshAgent>();
     ogm   = gameManager.GetComponent <OverallGameManager>();
     ac    = GetComponentInChildren <AnimationController> ();
 }
예제 #39
0
 public void Start()
 {
     controller = GetComponent <AnimationController>();
 }
예제 #40
0
 public AnimationComponent() : base(ComponentTypeManager.GetType(typeof(AnimationComponent)))
 {
     Controller = new AnimationController();
 }
 // Start is called before the first frame update
 void Start()
 {
     logic = GameObject.FindGameObjectWithTag("Logic").GetComponent <Logic>();
     animationController = logic.GetComponent <AnimationController>();
 }
예제 #42
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            Main.Config settings  = main.Settings;
            Transform   transform = entity.GetOrCreate <Transform>("Transform");

            entity.CannotSuspend = true;

            PlayerFactory.Instance = entity;

            this.SetMain(entity, main);

            FPSInput input = new FPSInput();

            input.EnabledWhenPaused = false;
            entity.Add("Input", input);

            Updater parkour = entity.Create <Updater>();
            Updater jumper  = entity.Create <Updater>();

            Player player = entity.GetOrCreate <Player>("Player");

            AnimatedModel firstPersonModel = entity.GetOrCreate <AnimatedModel>("FirstPersonModel");

            firstPersonModel.MapContent            = false;
            firstPersonModel.Serialize             = false;
            firstPersonModel.Filename.Value        = "Models\\joan-firstperson";
            firstPersonModel.CullBoundingBox.Value = false;

            AnimatedModel model = entity.GetOrCreate <AnimatedModel>("Model");

            model.MapContent            = false;
            model.Serialize             = false;
            model.Filename.Value        = "Models\\joan";
            model.CullBoundingBox.Value = false;

            AnimationController anim       = entity.GetOrCreate <AnimationController>("AnimationController");
            RotationController  rotation   = entity.GetOrCreate <RotationController>("Rotation");
            BlockPredictor      predictor  = entity.GetOrCreate <BlockPredictor>("BlockPredictor");
            Jump             jump          = entity.GetOrCreate <Jump>("Jump");
            RollKickSlide    rollKickSlide = entity.GetOrCreate <RollKickSlide>("RollKickSlide");
            Vault            vault         = entity.GetOrCreate <Vault>("Vault");
            WallRun          wallRun       = entity.GetOrCreate <WallRun>("WallRun");
            VoxelTools       voxelTools    = entity.GetOrCreate <VoxelTools>("VoxelTools");
            Footsteps        footsteps     = entity.GetOrCreate <Footsteps>("Footsteps");
            FallDamage       fallDamage    = entity.GetOrCreate <FallDamage>("FallDamage");
            CameraController cameraControl = entity.GetOrCreate <CameraController>("CameraControl");
            FPSCamera        fpsCamera     = entity.GetOrCreate <FPSCamera>("FPSCamera");

            fpsCamera.Enabled.Value = false;
            Rumble rumble = entity.GetOrCreate <Rumble>("Rumble");

            Property <Vector3> floor = new Property <Vector3>();

            transform.Add(new Binding <Vector3>(floor, () => transform.Position + new Vector3(0, player.Character.Height * -0.5f, 0), transform.Position, player.Character.Height));
            AkGameObjectTracker.Attach(entity, floor);

            predictor.Add(new Binding <Vector3>(predictor.FootPosition, floor));
            predictor.Add(new Binding <Vector3>(predictor.LinearVelocity, player.Character.LinearVelocity));
            predictor.Add(new Binding <float>(predictor.Rotation, rotation.Rotation));
            predictor.Add(new Binding <float>(predictor.MaxSpeed, player.Character.MaxSpeed));
            predictor.Add(new Binding <float>(predictor.JumpSpeed, player.Character.JumpSpeed));
            predictor.Add(new Binding <bool>(predictor.IsSupported, player.Character.IsSupported));

            jump.Add(new Binding <bool>(jump.Crouched, player.Character.Crouched));
            jump.Add(new TwoWayBinding <bool>(player.Character.IsSupported, jump.IsSupported));
            jump.Add(new TwoWayBinding <bool>(player.Character.HasTraction, jump.HasTraction));
            jump.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, jump.LinearVelocity));
            jump.Add(new TwoWayBinding <BEPUphysics.Entities.Entity>(jump.SupportEntity, player.Character.SupportEntity));
            jump.Add(new TwoWayBinding <Vector3>(jump.SupportVelocity, player.Character.SupportVelocity));
            jump.Add(new Binding <Vector2>(jump.AbsoluteMovementDirection, player.Character.MovementDirection));
            jump.Add(new Binding <WallRun.State>(jump.WallRunState, wallRun.CurrentState));
            jump.Add(new Binding <float>(jump.Rotation, rotation.Rotation));
            jump.Add(new Binding <Vector3>(jump.Position, transform.Position));
            jump.Add(new Binding <Vector3>(jump.FloorPosition, floor));
            jump.Add(new Binding <float>(jump.MaxSpeed, player.Character.MaxSpeed));
            jump.Add(new Binding <float>(jump.JumpSpeed, player.Character.JumpSpeed));
            jump.Add(new Binding <float>(jump.Mass, player.Character.Mass));
            jump.Add(new Binding <float>(jump.LastRollKickEnded, rollKickSlide.LastRollKickEnded));
            jump.Add(new Binding <Voxel>(jump.WallRunMap, wallRun.WallRunVoxel));
            jump.Add(new Binding <Direction>(jump.WallDirection, wallRun.WallDirection));
            jump.Add(new CommandBinding <Voxel, Voxel.Coord, Direction>(jump.WalkedOn, footsteps.WalkedOn));
            jump.Add(new CommandBinding(jump.DeactivateWallRun, (Action)wallRun.Deactivate));
            jump.Add(new CommandBinding <float>(jump.FallDamage, fallDamage.ApplyJump));
            jump.Predictor = predictor;
            jump.Bind(model);
            jump.Add(new TwoWayBinding <Voxel>(wallRun.LastWallRunMap, jump.LastWallRunMap));
            jump.Add(new TwoWayBinding <Direction>(wallRun.LastWallDirection, jump.LastWallDirection));
            jump.Add(new TwoWayBinding <bool>(rollKickSlide.CanKick, jump.CanKick));
            jump.Add(new TwoWayBinding <float>(player.Character.LastSupportedSpeed, jump.LastSupportedSpeed));

            wallRun.Add(new Binding <bool>(wallRun.IsSwimming, player.Character.IsSwimming));
            wallRun.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, wallRun.LinearVelocity));
            wallRun.Add(new TwoWayBinding <Vector3>(transform.Position, wallRun.Position));
            wallRun.Add(new TwoWayBinding <bool>(player.Character.IsSupported, wallRun.IsSupported));
            wallRun.Add(new CommandBinding(wallRun.LockRotation, (Action)rotation.Lock));
            wallRun.Add(new CommandBinding <float>(wallRun.UpdateLockedRotation, rotation.UpdateLockedRotation));
            vault.Add(new CommandBinding(wallRun.Vault, delegate() { vault.Go(true); }));
            wallRun.Predictor = predictor;
            wallRun.Add(new Binding <float>(wallRun.Height, player.Character.Height));
            wallRun.Add(new Binding <float>(wallRun.JumpSpeed, player.Character.JumpSpeed));
            wallRun.Add(new Binding <float>(wallRun.MaxSpeed, player.Character.MaxSpeed));
            wallRun.Add(new TwoWayBinding <float>(rotation.Rotation, wallRun.Rotation));
            wallRun.Add(new TwoWayBinding <bool>(player.Character.AllowUncrouch, wallRun.AllowUncrouch));
            wallRun.Add(new TwoWayBinding <bool>(player.Character.HasTraction, wallRun.HasTraction));
            wallRun.Add(new Binding <float>(wallRun.LastWallJump, jump.LastWallJump));
            player.Add(new Binding <WallRun.State>(player.Character.WallRunState, wallRun.CurrentState));

            input.Bind(rollKickSlide.RollKickButton, settings.RollKick);
            rollKickSlide.Add(new Binding <bool>(rollKickSlide.EnableCrouch, player.EnableCrouch));
            rollKickSlide.Add(new Binding <float>(rollKickSlide.Rotation, rotation.Rotation));
            rollKickSlide.Add(new Binding <bool>(rollKickSlide.IsSwimming, player.Character.IsSwimming));
            rollKickSlide.Add(new Binding <bool>(rollKickSlide.IsSupported, player.Character.IsSupported));
            rollKickSlide.Add(new Binding <Vector3>(rollKickSlide.FloorPosition, floor));
            rollKickSlide.Add(new Binding <float>(rollKickSlide.Height, player.Character.Height));
            rollKickSlide.Add(new Binding <float>(rollKickSlide.MaxSpeed, player.Character.MaxSpeed));
            rollKickSlide.Add(new Binding <float>(rollKickSlide.JumpSpeed, player.Character.JumpSpeed));
            rollKickSlide.Add(new Binding <Vector3>(rollKickSlide.SupportVelocity, player.Character.SupportVelocity));
            rollKickSlide.Add(new TwoWayBinding <bool>(wallRun.EnableEnhancedWallRun, rollKickSlide.EnableEnhancedRollSlide));
            rollKickSlide.Add(new TwoWayBinding <bool>(player.Character.AllowUncrouch, rollKickSlide.AllowUncrouch));
            rollKickSlide.Add(new TwoWayBinding <bool>(player.Character.Crouched, rollKickSlide.Crouched));
            rollKickSlide.Add(new TwoWayBinding <bool>(player.Character.EnableWalking, rollKickSlide.EnableWalking));
            rollKickSlide.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, rollKickSlide.LinearVelocity));
            rollKickSlide.Add(new TwoWayBinding <Vector3>(transform.Position, rollKickSlide.Position));
            rollKickSlide.Predictor = predictor;
            rollKickSlide.Bind(model);
            rollKickSlide.VoxelTools = voxelTools;
            rollKickSlide.Add(new CommandBinding(rollKickSlide.DeactivateWallRun, (Action)wallRun.Deactivate));
            rollKickSlide.Add(new CommandBinding(rollKickSlide.Footstep, footsteps.Footstep));
            rollKickSlide.Add(new CommandBinding(rollKickSlide.LockRotation, (Action)rotation.Lock));
            SoundKiller.Add(entity, AK.EVENTS.STOP_PLAYER_SLIDE_LOOP);

            vault.Add(new Binding <Vector3>(vault.Position, transform.Position));
            vault.Add(new Binding <Vector3>(vault.FloorPosition, floor));
            vault.Add(new Binding <float>(vault.MaxSpeed, player.Character.MaxSpeed));
            vault.Add(new Binding <WallRun.State>(vault.WallRunState, wallRun.CurrentState));
            vault.Add(new CommandBinding(vault.LockRotation, (Action)rotation.Lock));
            vault.Add(new CommandBinding(vault.DeactivateWallRun, (Action)wallRun.Deactivate));
            vault.Add(new TwoWayBinding <float>(player.Character.LastSupportedSpeed, vault.LastSupportedSpeed));
            vault.Add(new CommandBinding <float>(vault.FallDamage, fallDamage.Apply));
            vault.Bind(model);
            vault.Predictor = predictor;
            vault.Add(new TwoWayBinding <float>(rotation.Rotation, vault.Rotation));
            vault.Add(new TwoWayBinding <bool>(player.Character.IsSupported, vault.IsSupported));
            vault.Add(new TwoWayBinding <bool>(player.Character.HasTraction, vault.HasTraction));
            vault.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, vault.LinearVelocity));
            vault.Add(new TwoWayBinding <bool>(player.Character.EnableWalking, vault.EnableWalking));
            vault.Add(new TwoWayBinding <bool>(player.Character.AllowUncrouch, vault.AllowUncrouch));
            vault.Add(new TwoWayBinding <bool>(player.Character.Crouched, vault.Crouched));
            vault.Add(new Binding <float>(vault.Radius, player.Character.Radius));

            rotation.Add(new TwoWayBinding <Vector2>(rotation.Mouse, input.Mouse));
            rotation.Add(new Binding <bool>(rotation.Rolling, rollKickSlide.Rolling));
            rotation.Add(new Binding <bool>(rotation.Kicking, rollKickSlide.Kicking));
            rotation.Add(new Binding <Vault.State>(rotation.VaultState, vault.CurrentState));
            rotation.Add(new Binding <WallRun.State>(rotation.WallRunState, wallRun.CurrentState));

            voxelTools.Add(new Binding <float>(voxelTools.Height, player.Character.Height));
            voxelTools.Add(new Binding <float>(voxelTools.SupportHeight, player.Character.SupportHeight));
            voxelTools.Add(new Binding <Vector3>(voxelTools.Position, transform.Position));

            anim.Add(new Binding <bool>(anim.IsSupported, player.Character.IsSupported));
            anim.Add(new Binding <WallRun.State>(anim.WallRunState, wallRun.CurrentState));
            anim.Add(new Binding <bool>(anim.EnableWalking, player.Character.EnableWalking));
            anim.Add(new Binding <bool>(anim.Crouched, player.Character.Crouched));
            anim.Add(new Binding <Vector3>(anim.LinearVelocity, player.Character.LinearVelocity));
            anim.Add(new Binding <Vector2>(anim.Movement, input.Movement));
            anim.Add(new Binding <Vector2>(anim.Mouse, input.Mouse));
            anim.Add(new Binding <float>(anim.Rotation, rotation.Rotation));
            anim.Add(new Binding <Voxel>(anim.WallRunMap, wallRun.WallRunVoxel));
            anim.Add(new Binding <Direction>(anim.WallDirection, wallRun.WallDirection));
            anim.Add(new Binding <bool>(anim.IsSwimming, player.Character.IsSwimming));
            anim.Add(new Binding <bool>(anim.Kicking, rollKickSlide.Kicking));
            anim.Add(new Binding <Vector3>(anim.SupportVelocity, player.Character.SupportVelocity));
            anim.Add
            (
                new Binding <bool>
                (
                    anim.EnableLean,
                    () => player.Character.EnableWalking.Value && player.Character.IsSupported.Value && input.Movement.Value.Y > 0.5f,
                    player.Character.EnableWalking, player.Character.IsSupported, input.Movement
                )
            );
            anim.Bind(model);

            // Camera control
            model.UpdateWorldTransforms();

            cameraControl.Add(new Binding <Vector2>(cameraControl.Mouse, input.Mouse));
            cameraControl.Add(new Binding <float>(cameraControl.Lean, x => x * (float)Math.PI * 0.05f, anim.Lean));
            cameraControl.Add(new Binding <Vector3>(cameraControl.LinearVelocity, player.Character.LinearVelocity));
            cameraControl.Add(new Binding <float>(cameraControl.MaxSpeed, player.Character.MaxSpeed));
            cameraControl.Add(new Binding <Matrix>(cameraControl.CameraBone, model.GetBoneTransform("Camera")));
            cameraControl.Add(new Binding <Matrix>(cameraControl.HeadBone, model.GetBoneTransform("ORG-head")));
            cameraControl.Add(new Binding <Matrix>(cameraControl.ModelTransform, model.Transform));
            cameraControl.Add(new Binding <float>(cameraControl.BaseCameraShakeAmount, () => MathHelper.Clamp((player.Character.LinearVelocity.Value.Length() - (player.Character.MaxSpeed * 2.5f)) / (player.Character.MaxSpeed * 4.0f), 0, 1), player.Character.LinearVelocity, player.Character.MaxSpeed));
            cameraControl.Offset = model.GetBoneTransform("Camera").Value.Translation - model.GetBoneTransform("ORG-head").Value.Translation;

            float heightOffset = 0.1f;

#if VR
            if (main.VR)
            {
                heightOffset = 0.4f;
            }
#endif
            cameraControl.Offset += new Vector3(0, heightOffset, 0);

            rumble.Add(new Binding <float>(rumble.CameraShake, cameraControl.TotalCameraShake));
            rumble.Add(new CommandBinding <float>(fallDamage.Rumble, rumble.Go));
            rumble.Add(new CommandBinding <float>(player.Rumble, rumble.Go));
            rumble.Add(new CommandBinding <float>(rollKickSlide.Rumble, rumble.Go));

            firstPersonModel.Add(new Binding <bool>(firstPersonModel.Enabled, x => !x, cameraControl.ThirdPerson));

            model.Add(new ChangeBinding <bool>(cameraControl.ThirdPerson, delegate(bool old, bool value)
            {
                if (value && !old)
                {
                    model.UnsupportedTechniques.Remove(Technique.Clip);
                    model.UnsupportedTechniques.Remove(Technique.Render);
                }
                else if (old && !value)
                {
                    model.UnsupportedTechniques.Add(Technique.Clip);
                    model.UnsupportedTechniques.Add(Technique.Render);
                }
            }));

            Lemma.Console.Console.AddConCommand(new Console.ConCommand("third_person", "Toggle third-person view (WARNING: EXPERIMENTAL)", delegate(Console.ConCommand.ArgCollection args)
            {
                cameraControl.ThirdPerson.Value = !cameraControl.ThirdPerson;
            }));
            entity.Add(new CommandBinding(entity.Delete, delegate()
            {
                Lemma.Console.Console.RemoveConCommand("third_person");
            }));

#if DEVELOPMENT
            ModelAlpha debugCylinder = new ModelAlpha();
            debugCylinder.Filename.Value = "AlphaModels\\cylinder";
            debugCylinder.Add(new Binding <Matrix>(debugCylinder.Transform, transform.Matrix));
            debugCylinder.Serialize   = false;
            debugCylinder.Alpha.Value = 0.25f;
            debugCylinder.Add(new Binding <bool>(debugCylinder.Enabled, cameraControl.ThirdPerson));
            debugCylinder.Add(new Binding <Vector3>(debugCylinder.Scale, delegate()
            {
                return(new Vector3(player.Character.Radius * 2.0f, player.Character.Height, player.Character.Radius * 2.0f));
            }, player.Character.Height, player.Character.Radius));
            entity.Add(debugCylinder);
#endif

            // When rotation is locked, we want to make sure the player can't turn their head
            // 180 degrees from the direction they're facing

#if VR
            if (main.VR)
            {
                input.MaxY.Value = input.MinY.Value = 0;
            }
            else
#endif
            input.Add(new Binding <float>(input.MaxY, () => rotation.Locked ? (float)Math.PI * 0.3f : (float)Math.PI * 0.4f, rotation.Locked));

            input.Add(new Binding <float>(input.MinX, () => rotation.Locked ? rotation.Rotation + ((float)Math.PI * -0.4f) : 0.0f, rotation.Rotation, rotation.Locked));
            input.Add(new Binding <float>(input.MaxX, () => rotation.Locked ? rotation.Rotation + ((float)Math.PI * 0.4f) : 0.0f, rotation.Rotation, rotation.Locked));
            input.Add(new NotifyBinding(delegate() { input.Mouse.Changed(); }, rotation.Locked));             // Make sure the rotation locking takes effect even if the player doesn't move the mouse

            // Setup rendering properties

            model.Materials = firstPersonModel.Materials = new Model.Material[3];

            // Hoodie and shoes
            model.Materials[0] = new Model.Material
            {
                SpecularIntensity = 0.0f,
                SpecularPower     = 1.0f,
            };

            // Hands
            model.Materials[1] = new Model.Material
            {
                SpecularIntensity = 0.3f,
                SpecularPower     = 2.0f,
            };

            // Pants and skin
            model.Materials[2] = new Model.Material
            {
                SpecularIntensity = 0.5f,
                SpecularPower     = 20.0f,
            };

            firstPersonModel.Bind(model);

            // Third person model only gets rendered for shadows. No regular rendering or reflections.
            model.UnsupportedTechniques.Add(Technique.Clip);
            model.UnsupportedTechniques.Add(Technique.Render);

            // First-person model only used for regular rendering. No shadows or reflections.
            firstPersonModel.UnsupportedTechniques.Add(Technique.Shadow);
            firstPersonModel.UnsupportedTechniques.Add(Technique.Clip);

            // Build UI
            UIRenderer ui = new UIRenderer();
            ui.DrawOrder.Value   = -1;
            ui.EnabledWhenPaused = true;
            ui.EnabledInEditMode = false;
            entity.Add("UI", ui);

            input.Add(new Binding <float>(input.MouseSensitivity, settings.MouseSensitivity));
            input.Add(new Binding <bool>(input.InvertMouseX, settings.InvertMouseX));
            input.Add(new Binding <bool>(input.InvertMouseY, settings.InvertMouseY));
            input.Add(new Binding <PCInput.PCInputBinding>(input.LeftKey, settings.Left));
            input.Add(new Binding <PCInput.PCInputBinding>(input.RightKey, settings.Right));
            input.Add(new Binding <PCInput.PCInputBinding>(input.BackwardKey, settings.Backward));
            input.Add(new Binding <PCInput.PCInputBinding>(input.ForwardKey, settings.Forward));

            model.StartClip("Idle", 0, true, AnimatedModel.DefaultBlendTime);

            // Set up AI agent
            Agent agent = entity.GetOrCreate <Agent>();
            agent.Add(new TwoWayBinding <float>(player.Health, agent.Health));
            agent.Add(new Binding <Vector3>(agent.Position, () => transform.Position.Value + new Vector3(0, player.Character.Height * -0.5f, 0), transform.Position, player.Character.Height));
            agent.Add(new Binding <bool>(agent.Loud, () => player.Character.MovementDirection.Value.LengthSquared() > 0 && !player.Character.Crouched, player.Character.Crouched));

            // Blocks
            BlockCloud blockCloud = entity.GetOrCreate <BlockCloud>("BlockCloud");
            blockCloud.Scale.Value = 0.5f;
            blockCloud.Add(new Binding <Vector3>(blockCloud.Position, () => transform.Position.Value + new Vector3(0, player.Character.Height + player.Character.LinearVelocity.Value.Y, 0), transform.Position, player.Character.Height, player.Character.LinearVelocity));
            blockCloud.Blocks.ItemAdded += delegate(int index, Entity.Handle block)
            {
                Entity e = block.Target;
                if (e != null)
                {
                    e.Serialize = false;
                    PhysicsBlock.CancelPlayerCollisions(e.Get <PhysicsBlock>());
                }
            };

            PointLight blockLight = entity.Create <PointLight>();
            blockLight.Add(new Binding <Vector3>(blockLight.Position, blockCloud.AveragePosition));
            blockLight.Add(new Binding <bool, int>(blockLight.Enabled, x => x > 0, blockCloud.Blocks.Length));
            blockLight.Attenuation.Value = 30.0f;
            blockLight.Add(new Binding <Vector3, Voxel.t>(blockLight.Color, delegate(Voxel.t t)
            {
                switch (t)
                {
                case Voxel.t.GlowBlue:
                    return(new Vector3(0.7f, 0.7f, 0.9f));

                case Voxel.t.GlowYellow:
                    return(new Vector3(0.9f, 0.9f, 0.7f));

                default:
                    return(new Vector3(0.8f, 0.8f, 0.8f));
                }
            }, blockCloud.Type));

            // Death
            entity.Add(new CommandBinding(player.Die, blockCloud.Clear));
            entity.Add(new CommandBinding(player.Die, delegate()
            {
                Session.Recorder.Event(main, "Die");
                if (agent.Killed || Agent.Query(transform.Position, 0.0f, 10.0f, x => x != agent) != null)
                {
                    Session.Recorder.Event(main, "Killed");
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_PLAYER_DEATH, entity);
                    main.Spawner.RespawnDistance = Spawner.KilledRespawnDistance;
                    main.Spawner.RespawnInterval = Spawner.KilledRespawnInterval;
                }
                entity.Add(new Animation(new Animation.Execute(entity.Delete)));
            }));

            player.EnabledInEditMode = false;

            Action updateFallSound = delegate()
            {
                float speed    = player.Character.LinearVelocity.Value.Length();
                float maxSpeed = player.Character.MaxSpeed * 1.25f;
                float value;
                if (speed > maxSpeed)
                {
                    value = (speed - maxSpeed) / (maxSpeed * 2.0f);
                }
                else
                {
                    value = 0.0f;
                }
                AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.SFX_PLAYER_FALL, value);
            };
            updateFallSound();
            AkSoundEngine.PostEvent(AK.EVENTS.PLAY_PLAYER_FALL, entity);
            player.Add(new NotifyBinding(updateFallSound, player.Character.LinearVelocity));
            SoundKiller.Add(entity, AK.EVENTS.STOP_PLAYER_FALL);

            player.Add(new TwoWayBinding <Matrix>(transform.Matrix, player.Character.Transform));

            model.Add(new Binding <Matrix>(model.Transform, delegate()
            {
                const float leanAmount = (float)Math.PI * 0.1f;
                return(Matrix.CreateTranslation(0, (player.Character.Height * -0.5f) - player.Character.SupportHeight, 0) * Matrix.CreateRotationZ(anim.Lean * leanAmount) * Matrix.CreateRotationY(rotation.Rotation) * transform.Matrix);
            }, transform.Matrix, rotation.Rotation, player.Character.Height, player.Character.SupportHeight, anim.Lean));

            firstPersonModel.Add(new Binding <Matrix>(firstPersonModel.Transform, model.Transform));
            firstPersonModel.Add(new Binding <Vector3>(firstPersonModel.Scale, model.Scale));

            WallRun.State[] footstepWallrunStates = new[]
            {
                WallRun.State.Left,
                WallRun.State.Right,
                WallRun.State.Straight,
                WallRun.State.None,
            };
            footsteps.Add(new Binding <bool>(footsteps.SoundEnabled, () => !player.Character.Crouched && footstepWallrunStates.Contains(wallRun.CurrentState) || (player.Character.IsSupported && player.Character.EnableWalking), player.Character.IsSupported, player.Character.EnableWalking, wallRun.CurrentState, player.Character.Crouched));
            footsteps.Add(new Binding <Vector3>(footsteps.Position, transform.Position));
            footsteps.Add(new Binding <float>(footsteps.Rotation, rotation.Rotation));
            footsteps.Add(new Binding <float>(footsteps.CharacterHeight, player.Character.Height));
            footsteps.Add(new Binding <float>(footsteps.SupportHeight, player.Character.SupportHeight));
            footsteps.Add(new Binding <bool>(footsteps.IsSupported, player.Character.IsSupported));
            footsteps.Add(new Binding <bool>(footsteps.IsSwimming, player.Character.IsSwimming));
            footsteps.Add(new CommandBinding <float>(footsteps.Damage, agent.Damage));
            footsteps.Add(new CommandBinding <Voxel, Voxel.Coord, Direction>(wallRun.WalkedOn, footsteps.WalkedOn));
            model.Trigger("Run", 0.16f, footsteps.Footstep);
            model.Trigger("Run", 0.58f, footsteps.Footstep);
            model.Trigger("WallRunLeft", 0.16f, footsteps.Footstep);
            model.Trigger("WallRunLeft", 0.58f, footsteps.Footstep);
            model.Trigger("WallRunRight", 0.16f, footsteps.Footstep);
            model.Trigger("WallRunRight", 0.58f, footsteps.Footstep);
            model.Trigger("WallRunStraight", 0.16f, footsteps.Footstep);
            model.Trigger("WallRunStraight", 0.58f, footsteps.Footstep);
            model.Trigger("TurnLeft", 0.15f, footsteps.Footstep);
            model.Trigger("TurnRight", 0.15f, footsteps.Footstep);
            model.Trigger("TopOut", 1.0f, new Command
            {
                Action = delegate()
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_PLAYER_GRUNT, entity);
                }
            });

            main.UI.IsMouseVisible.Value = false;

            SkinnedModel.Clip sprintAnimation = model["Sprint"], runAnimation = model["Run"];

            // Movement binding
            player.Add(new Binding <Vector2>(player.Character.MovementDirection, delegate()
            {
                Vector2 movement = input.Movement;
                if (movement.LengthSquared() == 0.0f)
                {
                    return(Vector2.Zero);
                }

                Matrix matrix = Matrix.CreateRotationY(rotation.Rotation);

                Vector2 forwardDir = new Vector2(matrix.Forward.X, matrix.Forward.Z);
                Vector2 rightDir   = new Vector2(matrix.Right.X, matrix.Right.Z);
                return(-(forwardDir * movement.Y) - (rightDir * movement.X));
            }, input.Movement, rotation.Rotation));

            player.Character.Crouched.Value      = true;
            player.Character.AllowUncrouch.Value = true;

            // Fall damage
            fallDamage.Add(new Binding <bool>(fallDamage.IsSupported, player.Character.IsSupported));
            fallDamage.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, fallDamage.LinearVelocity));
            fallDamage.Add(new TwoWayBinding <float>(player.Health, fallDamage.Health));
            fallDamage.Add(new CommandBinding <BEPUphysics.BroadPhaseEntries.Collidable, ContactCollection>(player.Character.Collided, fallDamage.Collided));
            fallDamage.Add(new TwoWayBinding <bool>(player.Character.EnableWalking, fallDamage.EnableWalking));
            fallDamage.Add(new TwoWayBinding <bool>(player.EnableMoves, fallDamage.EnableMoves));
            fallDamage.Add(new TwoWayBinding <bool>(fallDamage.Landing, rotation.Landing));
            fallDamage.Add(new CommandBinding(fallDamage.LockRotation, (Action)rotation.Lock));
            fallDamage.Add(new CommandBinding <float>(fallDamage.PhysicsDamage, agent.Damage));
            fallDamage.Bind(model);

            // Swim up
            input.Bind(player.Character.SwimUp, settings.Jump);

            float       parkourTime = 0;
            float       jumpTime    = 0;
            const float gracePeriod = 1.0f;
            jumper.Action = delegate(float dt)
            {
                if (player.EnableMoves && player.Character.EnableWalking &&
                    vault.CurrentState.Value == Vault.State.None &&
                    !rollKickSlide.Rolling && !rollKickSlide.Kicking &&
                    jumpTime < gracePeriod)
                {
                    if (jump.Go())
                    {
                        parkour.Enabled.Value = false;
                        jumper.Enabled.Value  = false;
                    }
                    jumpTime += dt;
                }
                else
                {
                    jumper.Enabled.Value = false;
                }
            };
            jumper.Add(new CommandBinding(jumper.Enable, delegate() { jumpTime = 0; }));
            jumper.Enabled.Value = false;
            entity.Add(jumper);

            // Jumping
            input.Bind(settings.Jump, PCInput.InputState.Down, delegate()
            {
                jumper.Enabled.Value = true;
            });

            input.Bind(settings.Jump, PCInput.InputState.Up, delegate()
            {
                jumper.Enabled.Value = false;
            });

            // Wall-run, vault, predictive
            parkour.Action = delegate(float dt)
            {
                if (player.EnableMoves &&
                    player.Character.EnableWalking &&
                    !(player.Character.Crouched && player.Character.IsSupported) &&
                    vault.CurrentState.Value == Vault.State.None &&
                    !rollKickSlide.Kicking &&
                    !rollKickSlide.Rolling &&
                    wallRun.CurrentState.Value == WallRun.State.None &&
                    parkourTime < gracePeriod)
                {
                    bool didSomething = false;

                    bool parkourBeganThisFrame = parkourTime == 0;
                    if (predictor.PossibilityCount > 0)
                    {
                        // In slow motion, prefer left and right wall-running
                        if (!(didSomething = wallRun.Activate(WallRun.State.Left, parkourBeganThisFrame)))
                        {
                            if (!(didSomething = wallRun.Activate(WallRun.State.Right, parkourBeganThisFrame)))
                            {
                                if (!(didSomething = vault.Go(parkourBeganThisFrame)))
                                {
                                    didSomething = wallRun.Activate(WallRun.State.Straight, parkourBeganThisFrame);
                                }
                            }
                        }
                    }
                    else
                    {
                        // In normal mode, prefer straight wall-running
                        if (!(didSomething = vault.Go(parkourBeganThisFrame)))
                        {
                            if (!(didSomething = wallRun.Activate(WallRun.State.Straight, parkourBeganThisFrame)))
                            {
                                if (!(didSomething = wallRun.Activate(WallRun.State.Left, parkourBeganThisFrame)))
                                {
                                    didSomething = wallRun.Activate(WallRun.State.Right, parkourBeganThisFrame);
                                }
                            }
                        }
                    }

                    if (didSomething)
                    {
                        jumper.Enabled.Value    = false;
                        player.SlowMotion.Value = false;
                        parkour.Enabled.Value   = false;
                    }
                    else if (parkourBeganThisFrame)
                    {
                        if (blockCloud.Blocks.Length > 0)
                        {
                            player.SlowMotion.Value = true;
                            predictor.ClearPossibilities();
                            predictor.PredictPlatforms();
                            predictor.PredictWalls();
                        }
                        else if (player.EnableSlowMotion)
                        {
                            player.SlowMotion.Value = true;
                        }
                    }

                    parkourTime += dt;
                }
                else
                {
                    parkour.Enabled.Value = false;
                }
            };
            parkour.Add(new CommandBinding(parkour.Enable, delegate()
            {
                parkourTime = 0;
            }));
            entity.Add(parkour);
            parkour.Enabled.Value = false;

            input.Bind(settings.Parkour, PCInput.InputState.Down, delegate()
            {
                parkour.Enabled.Value = true;
            });

            input.Bind(settings.Parkour, PCInput.InputState.Up, delegate()
            {
                parkour.Enabled.Value = false;
                wallRun.Deactivate();
                if (player.SlowMotion)
                {
                    player.SlowMotion.Value = false;
                }
            });

            input.Bind(settings.RollKick, PCInput.InputState.Down, delegate()
            {
                if (player.EnableMoves && player.Character.EnableWalking)
                {
                    rollKickSlide.Go();
                    parkour.Enabled.Value = false;
                    jumper.Enabled.Value  = false;
                }
            });

            input.Bind(settings.RollKick, PCInput.InputState.Up, delegate()
            {
                if (!rollKickSlide.Rolling && !rollKickSlide.Kicking)
                {
                    player.Character.AllowUncrouch.Value = true;
                }
            });

            // Special ability

            /*
             * input.Bind(settings.SpecialAbility, PCInput.InputState.Down, delegate()
             * {
             *      Voxel.GlobalRaycastResult hit = Voxel.GlobalRaycast(main.Camera.Position, main.Camera.Forward, main.Camera.FarPlaneDistance, null);
             *      if (hit.Voxel != null && hit.Voxel.GetType() != typeof(DynamicVoxel))
             *      {
             *              VoxelRip.Go(hit.Voxel, hit.Coordinate.Value, 7, delegate(List<DynamicVoxel> results)
             *              {
             *                      foreach (DynamicVoxel v in results)
             *                      {
             *                              v.IsAffectedByGravity.Value = false;
             *                              v.LinearVelocity.Value = hit.Voxel.GetAbsoluteVector(hit.Normal.GetVector()) * 7.0f
             + new Vector3((float)this.random.NextDouble() * 2.0f - 1.0f, (float)this.random.NextDouble() * 2.0f - 1.0f, (float)this.random.NextDouble() * 2.0f - 1.0f);
             +                      }
             +              });
             +      }
             + });
             */

            // Player data bindings

            entity.Add(new PostInitialization
            {
                delegate()
                {
                    Entity dataEntity     = PlayerDataFactory.Instance;
                    PlayerData playerData = dataEntity.Get <PlayerData>();

                    // HACK. Overwriting the property rather than binding the two together. Oh well.
                    // This is because I haven't written a two-way list binding.
                    footsteps.RespawnLocations = playerData.RespawnLocations;

                    // Bind player data properties
                    entity.Add(new TwoWayBinding <float>(WorldFactory.Instance.Get <World>().CameraShakeAmount, cameraControl.CameraShakeAmount));
                    entity.Add(new TwoWayBinding <bool>(playerData.EnableRoll, rollKickSlide.EnableRoll));
                    entity.Add(new TwoWayBinding <bool>(playerData.EnableCrouch, player.EnableCrouch));
                    entity.Add(new TwoWayBinding <bool>(playerData.EnableKick, rollKickSlide.EnableKick));
                    entity.Add(new TwoWayBinding <bool>(playerData.EnableWallRun, wallRun.EnableWallRun));
                    entity.Add(new TwoWayBinding <bool>(playerData.EnableWallRunHorizontal, wallRun.EnableWallRunHorizontal));
                    entity.Add(new TwoWayBinding <bool>(playerData.EnableEnhancedWallRun, wallRun.EnableEnhancedWallRun));
                    entity.Add(new TwoWayBinding <bool>(playerData.EnableMoves, player.EnableMoves));
                    entity.Add(new TwoWayBinding <float>(playerData.MaxSpeed, player.Character.MaxSpeed));
                    entity.Add(new TwoWayBinding <Voxel.t>(playerData.CloudType, blockCloud.Type));
                    entity.Add(new TwoWayBinding <bool>(playerData.ThirdPerson, cameraControl.ThirdPerson));
                    entity.Add(new TwoWayBinding <bool>(playerData.EnableSlowMotion, player.EnableSlowMotion));

                    Phone phone = dataEntity.GetOrCreate <Phone>("Phone");

                    entity.Add
                    (
                        new Binding <bool>
                        (
                            phone.CanReceiveMessages,
                            () => player.Character.IsSupported && !player.Character.IsSwimming && !player.Character.Crouched,
                            player.Character.IsSupported,
                            player.Character.IsSwimming,
                            player.Character.Crouched
                        )
                    );

                    PhoneNote.Attach(main, entity, player, model, input, phone, player.Character.EnableWalking, playerData.PhoneActive, playerData.NoteActive);

                    PlayerUI.Attach(main, entity, ui, player.Health, rotation.Rotation, playerData.NoteActive, playerData.PhoneActive);
                }
            });

            fpsCamera.Add(new Binding <Vector2>(fpsCamera.Mouse, input.Mouse));
            fpsCamera.Add(new Binding <Vector2>(fpsCamera.Movement, input.Movement));
            input.Bind(fpsCamera.SpeedMode, settings.Parkour);
            input.Bind(fpsCamera.Up, settings.Jump);
            fpsCamera.Add(new Binding <bool>(fpsCamera.Down, input.GetKey(Keys.LeftControl)));
            Lemma.Console.Console.AddConCommand(new ConCommand("noclip", "Toggle free camera mode", delegate(ConCommand.ArgCollection args)
            {
                bool freeCameraMode            = !fpsCamera.Enabled;
                fpsCamera.Enabled.Value        = freeCameraMode;
                cameraControl.Enabled.Value    = !freeCameraMode;
                firstPersonModel.Enabled.Value = !freeCameraMode;
                model.Enabled.Value            = !freeCameraMode;
                ui.Enabled.Value = !freeCameraMode;
                player.Character.EnableWalking.Value      = !freeCameraMode;
                player.EnableMoves.Value                  = !freeCameraMode;
                player.Character.Body.IsAffectedByGravity = !freeCameraMode;
                if (freeCameraMode)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.STOP_PLAYER_BREATHING_SOFT, entity);
                }
                else
                {
                    transform.Position.Value = main.Camera.Position;
                }
            }));

            entity.Add(new CommandBinding(entity.Delete, delegate()
            {
                Lemma.Console.Console.RemoveConCommand("noclip");
                if (fpsCamera.Enabled)                 // Movement is disabled. Re-enable it.
                {
                    player.Character.EnableWalking.Value = true;
                    player.EnableMoves.Value             = true;
                }
                PlayerFactory.Instance = null;
            }));
        }
예제 #43
0
    public AnimationController animController; // A reference to the animationController, is used to switch dancing states.

    // This is called once, this then calls Initial Stats function
    void Awake()
    {
        InitialStats();
        animController = GetComponent <AnimationController>();
    }
예제 #44
0
파일: Model.cs 프로젝트: ARLM-Attic/xna-xen
        /// <summary>
        /// Draw the model. This class automatically assigns shaders when drawing
        /// </summary>
        /// <param name="state"></param>
        public void Draw(DrawState state)
        {
            if (modelData == null)
            {
                throw new InvalidOperationException("ModelData is null");
            }

            if (controller != null)
            {
                controller.WaitForAsyncAnimation(state, state.FrameIndex, true);

                if (controller.IsDisposed)
                {
                    controller = null;
                }
            }

            if (controller != null && hierarchy == null)
            {
                hierarchy = new MaterialAnimationTransformHierarchy(modelData.skeleton);
            }

            if (hierarchy != null)
            {
                hierarchy.UpdateTransformHierarchy(controller.transformedBones);
            }

            ModelInstanceShaderProvider shaderProvider = this.shaderProvider;
            MaterialLightCollection     lights         = this.lights;

            ShaderProviderFlag providerFlag;

            MaterialLightCollection.LightCollectionFlag lightsFlag;

            state.GetDrawFlag(out providerFlag);
            if (providerFlag.OverrideShaderProvider)
            {
                shaderProvider = providerFlag.ShaderProvider;
            }

            state.GetDrawFlag(out lightsFlag);
            if (lightsFlag.OverrideLightCollection)
            {
                lights = lightsFlag.LightCollection;
            }

            if (shaderProvider != null)
            {
                if (controller != null)
                {
                    shaderProvider.BeginDraw(state, controller.transformedBones, hierarchy.GetMatrixData());
                }
                else
                {
                    shaderProvider.BeginDraw(state);
                }
            }

            Vector3 boundsMin, boundsMax;

            ContainmentType cullModel = ContainmentType.Contains;

            //if there is just one geometry object, then the ICullable.CullTest() call will have been suficient.
            bool skipCullTest = this.modelData != null && this.modelData.meshes.Length == 1 && this.modelData.meshes[0].geometry.Length == 1;

            if (!skipCullTest)
            {
                if (controller != null)
                {
                    cullModel = state.Culler.IntersectBox(ref controller.boundsMin, ref controller.boundsMax);
                }
                else
                {
                    cullModel = state.Culler.IntersectBox(ref modelData.staticBounds.minimum, ref modelData.staticBounds.maximum);
                }
            }

            if (cullModel != ContainmentType.Disjoint)
            {
                for (int m = 0; m < modelData.meshes.Length; m++)
                {
                    MeshData mesh = modelData.meshes[m];

                    if (shaderProvider != null)
                    {
                        shaderProvider.BeginMesh(state, mesh);
                    }

                    ContainmentType cullMesh = cullModel;

                    if (cullModel == ContainmentType.Intersects && modelData.meshes.Length > 1)
                    {
                        if (controller != null)
                        {
                            controller.ComputeMeshBounds(m, out boundsMin, out boundsMax);
                            cullMesh = state.Culler.IntersectBox(ref boundsMin, ref boundsMax);
                        }
                        else
                        {
                            cullMesh = state.Culler.IntersectBox(ref mesh.staticBounds.minimum, ref mesh.staticBounds.maximum);
                        }
                    }

                    if (cullMesh != ContainmentType.Disjoint)
                    {
                        for (int g = 0; g < mesh.geometry.Length; g++)
                        {
                            GeometryData   geom   = mesh.geometry[g];
                            MaterialShader shader = geom.MaterialShader;

                            if (shaderProvider != null && shaderProvider.BeginGeometryShaderOverride(state, geom, lights))
                            {
                                shader = null;
                            }

                            bool cullTest = true;

                            if (cullMesh == ContainmentType.Intersects && mesh.geometry.Length > 1)
                            {
                                if (controller != null)
                                {
                                    controller.ComputeGeometryBounds(m, g, out boundsMin, out boundsMax);
                                    cullTest = state.Culler.TestBox(ref boundsMin, ref boundsMax);
                                }
                                else
                                {
                                    cullTest = state.Culler.TestBox(ref geom.staticBounds.minimum, ref geom.staticBounds.maximum);
                                }
                            }

                            if (cullTest)
                            {
                                if (shader != null)
                                {
                                    shader.AnimationTransforms = hierarchy;
                                    shader.Lights = lights;
                                    shader.Bind(state);
                                }

                                geom.Vertices.Draw(state, geom.Indices, PrimitiveType.TriangleList);
                            }

                            if (shaderProvider != null)
                            {
                                shaderProvider.EndGeometry(state, geom);
                            }
                        }
                    }

                    if (shaderProvider != null)
                    {
                        shaderProvider.EndMesh(state, mesh);
                    }
                }
            }

            if (shaderProvider != null)
            {
                shaderProvider.EndDraw(state);
            }
        }
예제 #45
0
        public static Animation ConvertFromAssimpScene(Ai.Scene aiScene, Ai.Animation aiAnimation, AnimationConverterOptions options)
        {
            var animation = new Animation(options.Version);

            animation.Duration = ConvertTime(aiAnimation.DurationInTicks, aiAnimation.TicksPerSecond);

            foreach (var aiChannel in aiAnimation.NodeAnimationChannels)
            {
                if (AssimpConverterCommon.MeshAttachmentNameRegex.IsMatch(aiChannel.NodeName))
                {
                    continue;
                }

                var nodeName = AssimpConverterCommon.UnescapeName(aiChannel.NodeName);

                var controller = new AnimationController(options.Version)
                {
                    TargetKind = TargetKind.Node,
                    TargetName = nodeName,
                    TargetId   = GetTargetIdForNode(aiScene.RootNode, nodeName)
                };

                var track = new KeyframeTrack(options.Version);

                // NodePRS only for now
                track.KeyframeType = KeyframeType.NodePRS;

                // Fetch the unique key frame timings from all position, rotation and scale keys.
                var keyframeTimings = aiChannel.PositionKeys
                                      .Select(x => x.Time)
                                      .Concat(aiChannel.RotationKeys.Select(x => x.Time))
                                      .Concat(aiChannel.ScalingKeys.Select(x => x.Time))
                                      .Distinct()
                                      .OrderBy(x => x);

                // Convert the times to our scale and save them.
                track.KeyframeTimings = keyframeTimings
                                        .Select(x => ConvertTime(x, aiAnimation.TicksPerSecond))
                                        .ToList();

                // Decompose the local transform of the affected node so we can use them as the base values for our keyframes
                aiScene.RootNode.FindNode(nodeName).Transform
                .Decompose(out var nodeBaseScale, out var nodeBaseRotation, out var nodeBaseTranslation);

                // Keep track of the last position, rotation and scale used to ensure that interpolation works properly
                var lastPosition = nodeBaseTranslation;
                var lastRotation = nodeBaseRotation;
                var lastScale    = nodeBaseScale;

                foreach (var time in keyframeTimings)
                {
                    // Start building the keyframe
                    var keyframe = new KeyframePRS(track.KeyframeType)
                    {
                        Position = new Vector3(lastPosition.X, lastPosition.Y, lastPosition.Z),
                        Rotation = new Quaternion(lastRotation.X, lastRotation.Y, lastRotation.Z, lastRotation.W),
                        Scale    = new Vector3(lastScale.X, lastScale.Y, lastScale.Z)
                    };

                    // Fetch the Assimp keys for this time
                    var aiPositionKey = aiChannel.PositionKeys.SingleOrDefault(x => x.Time == time);
                    var aiRotationKey = aiChannel.RotationKeys.SingleOrDefault(x => x.Time == time);
                    var aiScaleKey    = aiChannel.ScalingKeys.SingleOrDefault(x => x.Time == time);

                    if (aiPositionKey != default(Ai.VectorKey))
                    {
                        keyframe.Position = new Vector3(aiPositionKey.Value.X, aiPositionKey.Value.Y, aiPositionKey.Value.Z);
                        lastPosition      = aiPositionKey.Value;
                    }

                    if (aiRotationKey != default(Ai.QuaternionKey))
                    {
                        keyframe.Rotation = new Quaternion(aiRotationKey.Value.X, aiRotationKey.Value.Y, aiRotationKey.Value.Z,
                                                           aiRotationKey.Value.W);
                        lastRotation = aiRotationKey.Value;
                    }

                    if (aiScaleKey != default(Ai.VectorKey))
                    {
                        keyframe.Scale = new Vector3(aiScaleKey.Value.X, aiScaleKey.Value.Y, aiScaleKey.Value.Z);
                        lastScale      = aiScaleKey.Value;
                    }

                    track.Keyframes.Add(keyframe);
                }

                controller.Tracks.Add(track);
                animation.Controllers.Add(controller);
            }

            return(animation);
        }
예제 #46
0
 public override void RoomAction(int multiplier)
 {
     AnimationController.SetAnimation("EngineControl");
     EngineAction(multiplier);
 }
예제 #47
0
 private void Start()
 {
     rgb            = GetComponent <Rigidbody>();
     animController = GetComponent <AnimationController>();
     photonView     = GetComponent <PhotonView>();
 }
예제 #48
0
    void OnTriggerEnter(Collider other)
    {
        AnimationController anim = playerObject.GetComponent <AnimationController>();

        if (other.gameObject.CompareTag("Bead"))
        {
            other.gameObject.SetActive(false);

            audioSource.PlayOneShot(pickSound, audioVolume);

            beadCount += 1;

            panelScript.CubeController(beadCount);
        }

        else if (other.gameObject.CompareTag("SendingPoint"))
        {
            isOver = true;
            panelScript.OnClearPanel(beadCount, elapsedTime, HistoryManager.Instance.GetUsedNumOfScript());
            Debug.Log("clear");
        }

        else if (other.gameObject.CompareTag("LeftCar") || other.gameObject.CompareTag("RightCar") || other.gameObject.CompareTag("Train"))
        {
            //Time.timeScale = 0.6f;

            StartCoroutine("DeadDirection");

            isOver = true;
            anim.DeadAnim();
            audioSource.PlayOneShot(deadSound, audioVolume);
            Debug.Log("Game Over by Car");
        }

        else if (other.gameObject.CompareTag("Trap"))
        {
            //Time.timeScale = 0.6f;

            StartCoroutine("DeadDirection");

            trap_triggerd = other.transform.parent.GetChild(1);

            other.gameObject.SetActive(false);
            trap_triggerd.gameObject.SetActive(true);

            isOver = true;
            anim.TrapDeadAnim();
            audioSource.PlayOneShot(deadSound, audioVolume);
            Debug.Log("Game Over by Trap");
        }
        else if (other.gameObject.CompareTag("GasiOn"))
        {
            //Time.timeScale = 0.6f;

            StartCoroutine("DeadDirection");

            isOver = true;
            anim.DeadAnim();
            audioSource.PlayOneShot(deadSound, audioVolume);
            Debug.Log("Game Over by Gasi");
        }

        else if (other.gameObject.CompareTag("Stepping"))
        {
            stepScript = other.GetComponent <SteppingController>();
        }

        else if (other.gameObject.CompareTag("Arrow"))
        {
            //Time.timeScale = 0.6f;

            StartCoroutine("DeadDirection");

            isOver = true;
            anim.TrapDeadAnim();
            audioSource.PlayOneShot(deadSound, audioVolume);
            Debug.Log("Game Over by Arrow");
        }
    }
예제 #49
0
        public override void initState()
        {
            base.initState();
            m_HasMoreOld          = true;
            m_EmptyFocusNode      = new FocusNode();
            m_SenderFocusNode     = new FocusNode();
            m_ScrollController    = new ScrollController();
            m_AnimationController = new AnimationController(
                vsync: this,
                duration: new TimeSpan(0, 0, 0, 0, milliseconds: 240)
                );
            m_AnimationController.addListener(() => setState());
            m_AnimationController.addStatusListener(AnimationStatusListener);

            SchedulerBinding.instance.addPostFrameCallback(value =>
            {
                if (MediaQuery.of(context).size.width < 750)
                {
                    m_AnimationController.forward();
                }
            });

            m_ScrollController.addListener(() =>
            {
                if (m_ScrollController.offset < 50f && Window.NewMessages.isNotEmpty())
                {
                    var message = Window.NewMessages[0];
                    Window.NewMessages.RemoveAt(0);
                    var showTime = true;
                    if (!widget.messages[message.channelId].isEmpty())
                    {
                        var preMsg  = widget.messages[message.channelId].first();
                        var preTime = ExtractTimeFromSnowflakeId(preMsg.id ?? preMsg.nonce);
                        var curTime = ExtractTimeFromSnowflakeId(message.id ?? message.nonce);
                        showTime    = curTime - preTime > TimeSpan.FromMinutes(5);
                    }

                    var height = CalculateMessageHeight(
                        message,
                        showTime,
                        MediaQuery.of(context).size.width * 0.7f - 286.5f);
                    Window.Messages[message.channelId].Insert(0, message);
                    m_ScrollController.jumpTo(m_ScrollController.offset + height);
                    HomePage.currentState.setState();
                }
            });
            if (!widget.messages.ContainsKey(widget.channel.id) || widget.messages[widget.channel.id].isEmpty())
            {
                m_Initialized = false;
                widget.messages[widget.channel.id] = new List <Models.Message>();
                if (widget.pullFlags.ContainsKey(widget.channel.id) && widget.pullFlags[widget.channel.id])
                {
                    widget.pullFlags[widget.channel.id] = false;
                }

                SchedulerBinding.instance.addPostFrameCallback(value =>
                {
                    Promise.All(new List <IPromise>
                    {
                        Get <GetMembersResponse>(
                            $"/api/connectapp/v1/channels/{widget.channel.id}/members"
                            ).Then(response =>
                        {
                            if (!widget.members.ContainsKey(widget.channel.id))
                            {
                                widget.members[widget.channel.id] = new List <ChannelMember>();
                            }

                            response.list.ForEach(member =>
                            {
                                if (!widget.users.ContainsKey(member.user.id))
                                {
                                    widget.users.Add(member.user.id, member.user);
                                }

                                if (widget.members[widget.channel.id].All(m => m.user.id != member.user.id))
                                {
                                    widget.members[widget.channel.id].Add(member);
                                }
                            });
                            widget.hasMoreMembers[widget.channel.id] =
                                response.total > widget.members[widget.channel.id].Count;
                        }).Catch(exception => { }),
                        Utils.Get <GetMessagesResponse>(
                            $"/api/connectapp/v1/channels/{widget.channel.id}/messages"
                            ).Then(getMessagesResponse =>
                        {
                            if (mounted)
                            {
                                m_HasMoreOld  = getMessagesResponse.hasMore;
                                m_Initialized = true;
                            }

                            widget.messages[widget.channel.id] = getMessagesResponse.items;
                            m_HasMoreUnreads = true;
                            if (m_PreviousLastMsgId == null)
                            {
                                m_HasMoreUnreads = false;
                            }
                            else
                            {
                                foreach (var m in widget.messages[widget.channel.id])
                                {
                                    if (string.Compare(m.id, m_PreviousLastMsgId) > 0)
                                    {
                                        ++m_MsgsUnreads;
                                    }
                                    else
                                    {
                                        m_HasMoreUnreads = false;
                                        break;
                                    }
                                }
                            }
                        }).Catch(exception => { }),
                    }).Then(() =>
                    {
                        if (mounted)
                        {
                            using (WindowProvider.of(context).getScope())
                            {
                                setState();
                                FocusScope.of(context).requestFocus(m_SenderFocusNode);
                            }
                        }
                    });
                });
            }
            else
            {
                PullIfNeeded();
                m_Initialized    = true;
                m_HasMoreUnreads = true;
                if (m_PreviousLastMsgId == null)
                {
                    m_HasMoreUnreads = false;
                }
                else
                {
                    foreach (var m in widget.messages[widget.channel.id])
                    {
                        if (string.Compare(m.id, m_PreviousLastMsgId) > 0)
                        {
                            ++m_MsgsUnreads;
                        }
                        else
                        {
                            m_HasMoreUnreads = false;
                            break;
                        }
                    }
                }

                SchedulerBinding.instance.addPostFrameCallback(value =>
                {
                    using (WindowProvider.of(context).getScope())
                    {
                        FocusScope.of(context).requestFocus(m_SenderFocusNode);
                    }
                });
            }

            SchedulerBinding.instance.addPostFrameCallback(value =>
            {
                var rootState = HomePage.of(context);
                rootState.Ack(widget.channel.id);
            });
        }
예제 #50
0
 public ObjectAnimation(GameObject _gameObject, bool _ignorePause = false)
 {
     ignorePause = _ignorePause;
     AnimationController.Add(this);
     gameObject = _gameObject;
 }
예제 #51
0
 public LocomotionAnimationStateSystem(int animationLayer, AnimationController animationControllerRef) : this()
 {
     AnimationLayer         = animationLayer;
     AnimationControllerRef = animationControllerRef;
 }
예제 #52
0
 public void Initialize()
 {
     game = new BountyBandits.Game();
     game.resetPhysics();
     beingsMap = new Dictionary <String, Being>();
     foreach (BeingTypes beingType in Enum.GetValues(typeof(BeingTypes)))
     {
         beingsMap.Add(beingType.ToString(), new Being(beingType.ToString(), 1, AnimationController.fromXML(game.Content, beingType.ToString()), null, true, false));
     }
 }
예제 #53
0
 private void Start()
 {
     anim       = GetComponent <AnimationController>();
     animator   = FindObjectOfType <Animator>();
     changeFeed = FindObjectOfType <ChangeFlyState>();
 }
예제 #54
0
 public void attackComputeTest()
 {
     foreach (PlayerTypes playerType in Enum.GetValues(typeof(PlayerTypes)))
     {
         foreach (BeingTypes beingType in Enum.GetValues(typeof(BeingTypes)))
         {
             for (int level = 1; level < 99; level++)
             {
                 Being attacker = new Being("test-" + playerType.ToString(), level, AnimationController.fromXML(game.Content, playerType.ToString()), null, true, false);
                 Being target   = new Being("test-target-" + beingType.ToString(), level, AnimationController.fromXML(game.Content, beingType.ToString()), null, false, false);
                 attacker.body.Position = new Vector2(-48, 0);
                 target.body.Position   = new Vector2(48, 0);
                 attacker.isFacingLeft  = false;
                 target.isFacingLeft    = true;
                 attacker.setDepth(1);
                 target.setDepth(1);
                 float attackerDmg = attacker.attackCompute(target);
                 float targetDmg   = target.attackCompute(attacker);
                 Assert.IsTrue(attackerDmg > level / 2);
                 Assert.IsTrue(3 * targetDmg < attacker.getStat(BountyBandits.Stats.StatType.Life));
             }
         }
     }
 }
예제 #55
0
 // Start is called before the first frame update
 void Start()
 {
     anim = GetComponent <AnimationController>();
     rb   = GetComponent <Rigidbody2D>();
 }
예제 #56
0
 public override void Start()
 {
     base.Start();
     animController = GetComponent <Player>().animController;
 }
예제 #57
0
 // Use this for initialization
 void Start()
 {
     _animationController = this.GetComponent <AnimationController> ();
 }
예제 #58
0
                public void Update(Model9 model, float dtime, Matrix world)
                {
                    if (model != null && model.SkinnedMesh != null)
                    {
#if PROFILE_ANIMATIONS
                        if (ResetMatricesStart != null)
                        {
                            ResetMatricesStart();
                        }
#endif
                        ((CustomFrame)model.SkinnedMesh.RootFrame).ResetMatrices();
#if PROFILE_ANIMATIONS
                        if (ResetMatricesStop != null)
                        {
                            ResetMatricesStop();
                        }

                        if (SetupACStrat != null)
                        {
                            SetupACStrat();
                        }
#endif
                        if (TrackFadeTime[CurrentTrack] > 0)
                        {
#if DEBUG_ANIMATIONS
                            if (i % 15 == 0 && Entity.Name != "MainCharacter")
                            {
                                Console.WriteLine("Previous: " + (TrackFadeTime[CurrentTrack] / FadeTime));
                                Console.WriteLine("Current: " + (FadeTime - TrackFadeTime[CurrentTrack]) / FadeTime);
                            }
                            i++;
#endif

                            AnimationController.SetTrackWeight(previousTrack, TrackFadeTime[CurrentTrack] / FadeTime);
                            AnimationController.SetTrackWeight(CurrentTrack, (FadeTime - TrackFadeTime[CurrentTrack]) / FadeTime);
                            TrackFadeTime[CurrentTrack] -= dtime;
                        }
                        else
                        {
                            AnimationController.DisableTrack(previousTrack);
                            AnimationController.SetTrackSpeed(previousTrack, 0);
                            AnimationController.SetTrackWeight(previousTrack, 0);

                            AnimationController.SetTrackWeight(CurrentTrack, 1);
                        }

                        if (!TrackPaused[CurrentTrack] && !Looping[CurrentTrack])
                        {
                            if (TrackDurations[CurrentTrack] - dtime > 0)
                            {
                                TrackDurations[CurrentTrack] -= dtime;
                            }
                            else
                            {
                                TrackDurations[CurrentTrack] = 0;
                                AnimationController.SetTrackPosition(CurrentTrack, TrackDurations[CurrentTrack] - 0.01f);
                                AnimationController.SetTrackSpeed(CurrentTrack, 0);
                                TrackPaused[CurrentTrack] = true;
                                if (AnimationDone != null)
                                {
                                    AnimationDone(0);
                                }
                            }
                        }
#if PROFILE_ANIMATIONS
                        if (SetupACStop != null)
                        {
                            SetupACStop();
                        }

                        if (AdvanceTimeStart != null)
                        {
                            AdvanceTimeStart();
                        }
#endif
                        AnimationController.AdvanceTime(dtime, null);
#if PROFILE_ANIMATIONS
                        if (AdvanceTimeStop != null)
                        {
                            AdvanceTimeStop();
                        }

                        if (AdjustFrameMatricesStrat != null)
                        {
                            AdjustFrameMatricesStrat();
                        }
#endif
                        foreach (var v in FrameCustomValues)
                        {
#if DEBUG
                            if (v.Value.M22 == float.NaN || v.Value.M21 == float.NaN || v.Value.M23 == float.NaN || v.Value.M24 == float.NaN)
                            {
                                throw new Exception("Matrix contains NaN");
                            }
#endif
                            model.SkinnedMesh.ForEachFrame((f) =>
                            {
                                if (f.Name == v.Key)
                                {
                                    f.TransformationMatrix *= v.Value;
                                }
                            });
                        }
#if PROFILE_ANIMATIONS
                        if (AdjustFrameMatricesStop != null)
                        {
                            AdjustFrameMatricesStop();
                        }

                        if (UpdateMatricesStart != null)
                        {
                            UpdateMatricesStart();
                        }
#endif
                        model.SkinnedMesh.UpdateFrameMatrices(model.SkinnedMesh.RootFrame, world);
#if PROFILE_ANIMATIONS
                        if (UpdateMatricesStop != null)
                        {
                            UpdateMatricesStop();
                        }

                        if (StoreMatricesStart != null)
                        {
                            StoreMatricesStart();
                        }
#endif
                        foreach (var frame in SkinnedMesh.Frames)
                        {
                            if (frame.Name == "sword1" || frame.Name == "rifle" || frame.Name == "joint3")
                            {
                                FrameTransformation[frame] = frame.CombinedTransform;
                            }
                        }
                        foreach (Common.Tuple <CustomFrame, CustomMeshContainer> meshContainer in SkinnedMesh.MeshContainers)
                        {
                            string name = meshContainer.First.Name;

                            if (meshContainer.Second != null)
                            {
                                if (meshContainer.Second.SkinInfo != null)
                                {
                                    BoneCombination[] combinations = meshContainer.Second.BoneCombinations;

                                    Matrix[][] combinationMatrices = new Matrix[combinations.Length][];

                                    for (int i = 0; i < combinations.Length; i++)
                                    {
                                        Matrix[] boneMatrices = new Matrix[meshContainer.Second.PaletteEntries];

                                        for (int pe = 0; pe < meshContainer.Second.PaletteEntries; pe++)
                                        {
                                            int index = combinations[i].BoneIds[pe];
                                            if (index != -1)
                                            {
                                                boneMatrices[pe] = meshContainer.Second.BoneOffsets[index] *
                                                                   meshContainer.Second.BoneMatricesLookup[index].CombinedTransform;
                                            }
                                        }

                                        combinationMatrices[i] = boneMatrices;
                                    }

                                    StoredFrameMatrices[meshContainer.Second.MeshData.Mesh] = combinationMatrices;
                                }
                                else
                                {
                                    Matrix[][] combinedTransform = new Matrix[1][];

                                    combinedTransform[0] = new Matrix[] { meshContainer.First.CombinedTransform };

                                    StoredFrameMatrices[meshContainer.Second.MeshData.Mesh] = combinedTransform;
                                }
                            }
                        }
#if PROFILE_ANIMATIONS
                        if (StoreMatricesStop != null)
                        {
                            StoreMatricesStop();
                        }
#endif
                        //model.SkinnedMesh.ForEachFrame((frame) =>
                        //{
                        //    FrameTransformation[frame] = frame.CombinedTransform;

                        //    frame.ForEachMeshContainer((mc) =>
                        //    {
                        //        if (mc.SkinInfo != null)
                        //        {
                        //            BoneCombination[] combinations = mc.BoneCombinations;

                        //            Common.Tuple<Matrix[], Matrix[]>[] combinationMatrices =
                        //                new Common.Tuple<Matrix[], Matrix[]>[combinations.Length];

                        //            for (int i = 0; i < combinations.Length; i++)
                        //            {
                        //                Matrix[] boneMatrices = new Matrix[mc.PaletteEntries];
                        //                Matrix[] normalMatrices = new Matrix[mc.PaletteEntries];

                        //                for (int pe = 0; pe < mc.PaletteEntries; pe++)
                        //                {
                        //                    int index = combinations[i].BoneIds[pe];
                        //                    if (index != -1)
                        //                    {
                        //                        boneMatrices[pe] = mc.BoneOffsets[index] *
                        //                            mc.BoneMatricesLookup[index].CombinedTransform;
                        //                        normalMatrices[pe] = SlimDX.Matrix.Transpose(
                        //                            SlimDX.Matrix.Invert(boneMatrices[pe]));
                        //                    }
                        //                }

                        //                combinationMatrices[i] = new Common.Tuple<Matrix[], Matrix[]>(
                        //                    boneMatrices, normalMatrices);
                        //            }

                        //            StoredFrameMatrices[mc.MeshData.Mesh] = combinationMatrices;

                        //        }
                        //        else
                        //        {
                        //            Common.Tuple<Matrix[], Matrix[]>[] combinedTransform =
                        //                new Common.Tuple<Matrix[], Matrix[]>[1];

                        //            combinedTransform[0] = new Common.Tuple<Matrix[], Matrix[]>(
                        //                new Matrix[1] { frame.CombinedTransform },
                        //                new Matrix[1] { Matrix.Transpose(Matrix.Invert(frame.CombinedTransform)) });

                        //            StoredFrameMatrices[mc.MeshData.Mesh] = combinedTransform;
                        //        }
                        //    });
                        //});
                    }
                }
예제 #59
0
 public override AnimationController createAnimationController()
 {
     D.assert(_animationController == null);
     _animationController = BottomSheet.createAnimationController(navigator.overlay);
     return(_animationController);
 }
예제 #60
0
 /// <summary>
 /// This constructor creates an animation controller with the specified assetname
 /// </summary>
 /// <param name="center">the center position of the object.</param>
 /// <param name="width">the width of the object.</param>
 /// <param name="height">the height of the object.</param>
 /// <param name="assetName">the asset name to be used.</param>
 internal AnimatedObject(Vector2 center, int width, int height, string assetName) : base(center, width, height)
 {
     animationController = new AnimationController(assetName);
 }