Esempio n. 1
0
 /// <summary>
 /// Gets the element at the specified index.
 /// </summary>
 /// <param name="index">
 /// The index of the object to access.
 /// </param>
 /// <returns>
 /// The element at the specified index if one exists.
 /// </returns>
 /// <exception cref="IndexOutOfRangeException">
 /// The specified index is out of range.
 /// </exception>
 public T this[Int32 index]
 {
     get
     {
         using (var controlToken = StateControl.Enter())
         {
             var adjustedIndex = (ReadIndex + index);
             return (adjustedIndex < Capacity) ? ElementArray[adjustedIndex] : ElementArray[adjustedIndex - Capacity];
         }
     }
 }
Esempio n. 2
0
 private void OnTriggerEnter(Collider collision)
 {
     Debug.Log(this.name + " update state trigger enter:" + collision.gameObject.name);
     if (collision.Equals(colliderObject))
     {
         if (StateControl.getStateId() == currentState)
         {
             StateControl.nextState();
         }
     }
 }
Esempio n. 3
0
 void Update()
 {
     if (StateControl.GetState() != StateType.Playing || BirdManager.Instance.IsBirdDie)
     {
         return;
     }
     this.GetComponent <RectTransform>().localPosition += new Vector3(1, 0, 0) * _speed;
     if (this.GetComponent <RectTransform>().localPosition.x < -1900f)
     {
         ResetPosition();
     }
 }
        private ITopicClient CreateTopicClient <TMessage>()
            where TMessage : class
        {
            var topicPath = GetTopicPath <TMessage>();

            using (var controlToken = StateControl.Enter())
            {
                controlToken.AttachTask(EnsureTopicExistanceAsync(topicPath));
            }

            return(new TopicClient(Connection, topicPath, RetryBehavior));
        }
        private IQueueClient CreateQueueClient <TMessage>()
            where TMessage : class
        {
            var queuePath = GetQueuePath <TMessage>();

            using (var controlToken = StateControl.Enter())
            {
                controlToken.AttachTask(EnsureQueueExistanceAsync(queuePath));
            }

            return(new QueueClient(Connection, queuePath, ReceiveBehavior, RetryBehavior));
        }
        /// <summary>
        /// Unblocks waiting threads and ends the execution lifetime.
        /// </summary>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public void End()
        {
            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                if (IsAlive)
                {
                    EndOfLifeEvent.Set();
                    IsAlive = false;
                }
            }
        }
        private ISubscriptionClient CreateSubscriptionClient <TMessage>()
            where TMessage : class
        {
            var topicPath        = GetTopicPath <TMessage>();
            var subscriptionName = GetSubscriptionName <TMessage>();

            using (var controlToken = StateControl.Enter())
            {
                controlToken.AttachTask(EnsureSubscriptionExistanceAsync(topicPath, subscriptionName));
            }

            return(new SubscriptionClient(Connection, topicPath, subscriptionName, ReceiveBehavior, RetryBehavior));
        }
Esempio n. 8
0
 // Use this for initialization
 void Start()
 {
     if (Instance == null)
     {
         Instance = this;
         DontDestroyOnLoad(gameObject);
         currentStep = QUEST_STEP.START;
     }
     else if (Instance != this)
     {
         Destroy(gameObject);
     }
 }
Esempio n. 9
0
 /// <summary>
 /// 开启子状态控制器
 /// </summary>
 /// <param name="defaultStateId">子状态的默认状态</param>
 /// <param name="returnData">子状态接受的来自父状态的信息</param>
 /// <param name="receiveData">子状态发送到父状态的委托</param>
 public void StartChildStateControl(eStateId defaultStateId, object receiveData, Action <object> returnData)
 {
     _childControl = gameObject.GetComponent <StateControl>();
     if (_childControl == null)
     {
         _childControl = gameObject.AddComponent <StateControl>();
     }
     _childControl.enabled        = true;
     _childControl.IsChildControl = true;
     _childControl.SendAction     = returnData;
     _childControl.ReceiveData    = receiveData;
     _childControl.SetCurState(defaultStateId);
 }
Esempio n. 10
0
        /// <summary>
        /// Instructs the current <see cref="ReferenceManager" /> to manage the specified object.
        /// </summary>
        /// <typeparam name="T">
        /// The type of the managed object.
        /// </typeparam>
        /// <param name="reference">
        /// The managed object.
        /// </param>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public void AddObject <T>(T reference)
            where T : class
        {
            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();
                var managedReference = new ManagedReference <T>(reference);

                if (References.Contains(managedReference) == false)
                {
                    References.Enqueue(managedReference);
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Updates the specified entities in the current <see cref="DataAccessRepository{TEntity}" />.
        /// </summary>
        /// <param name="entities">
        /// The entities to update.
        /// </param>
        /// <exception cref="ArgumentException">
        /// <paramref name="entities" /> contains one or more null references.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="entities" /> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public void UpdateRange(IEnumerable <TEntity> entities)
        {
            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                if (entities.RejectIf().IsNull(nameof(entities)).TargetArgument.Any(entity => entity is null))
                {
                    throw new ArgumentException("The specified entity collection contains one or more null entities.", nameof(entities));
                }

                UpdateRange(entities, controlToken);
            }
        }
        /// <summary>
        /// Blocks the current thread until <see cref="End" /> or <see cref="Dispose" /> is invoked.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// The service execution lifetime has ended.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public void KeepAlive()
        {
            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                if (IsAlive == false)
                {
                    throw new InvalidOperationException("The service execution lifetime has ended.");
                }
            }

            EndOfLifeEvent.WaitOne();
        }
Esempio n. 13
0
        /// <summary>
        /// Updates the specified entity in the current <see cref="DataAccessRepository{TEntity}" />, or adds it if it doesn't exist.
        /// </summary>
        /// <param name="entity">
        /// The entity to add or update.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="entity" /> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public void AddOrUpdate(TEntity entity)
        {
            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                if (Contains(entity.RejectIf().IsNull(nameof(entity)).TargetArgument, controlToken))
                {
                    Update(entity, controlToken);
                    return;
                }

                Add(entity, controlToken);
            }
        }
Esempio n. 14
0
        private void Generate(string idProfile, StateControl sc, Visualizers.Types flags, Dictionary <Visualizers.Types, string> filenames)
        {
            var sett = new GeneratorSetting()
            {
                ProfileID    = /*"101113754039426612780"*/ idProfile,
                Rules        = rules,
                VisLogs      = (Visualizers.Types)flags,
                LogFiles     = filenames,
                MaxResults   = Convert.ToInt32(nudMaxRes.Value),
                MaxComments  = Convert.ToInt32(nudMaxComment.Value),
                MaxPluses    = Convert.ToInt32(nudMaxPlus.Value),
                MaxReshares  = Convert.ToInt32(nudMaxReshare.Value),
                Deep         = cbDeep.Checked ? Convert.ToInt32(nudDeep.Value) : 0,
                UseDateRange = cbDateRange.Checked,
                DateFrom     = Convert.ToDateTime(dtpFrom.Value.Date),
                DateTo       = Convert.ToDateTime(dtpTo.Value.AddDays(1).Date)
            };

            if (tcGooglePlus.SelectedTab == tpGPUsers)
            {
                sett.Methods = new Dictionary <Visualizers.Types, GeneratorLogsMeth> {
                    //UD
                    { Visualizers.Code_swarm, UDGenerator.LogGen },
                    { Visualizers.Gource, Generator.LogGen },
                    { Visualizers.Logstalgia, Generator.LogGen },
                    { Visualizers.Gephi, Generator.LogGen },
                };
                if (cbFGraph.Checked)
                {
                    new FollowersGenerator(apikey.Text, sc).Run(sett);
                }
                else
                {
                    (Program.OAuth2 != null ? new Generator(Program.OAuth2, sc) : new Generator(apikey.Text, sc)).Run(sett);
                }
            }
            else
            {
                sett.Methods = new Dictionary <Visualizers.Types, GeneratorLogsMeth> {
                    //UD
                    { Visualizers.Code_swarm, WordsSearchGenerator.LogGen },
                    { Visualizers.Gource, WordsSearchGenerator.LogGen },
                    { Visualizers.Logstalgia, WordsSearchGenerator.LogGen },
                    { Visualizers.Gephi, WordsSearchGenerator.LogGen },
                };
                (Program.OAuth2 != null ? new WordsSearchGenerator(Program.OAuth2, sc) : new WordsSearchGenerator(apikey.Text, sc)).Run(sett);
            }
        }
        /// <summary>
        /// Releases all resources consumed by the current <see cref="AzureServiceBusClientManager" />.
        /// </summary>
        /// <param name="disposing">
        /// A value indicating whether or not managed resources should be released.
        /// </param>
        protected override void Dispose(Boolean disposing)
        {
            try
            {
                if (disposing)
                {
                    using (var controlToken = StateControl.Enter())
                    {
                        if (LazyReceiveClientDictionary.IsValueCreated)
                        {
                            foreach (var client in ReceiveClientDictionary.Values)
                            {
                                if (client.IsClosedOrClosing)
                                {
                                    continue;
                                }

                                if (client is SubscriptionClient subscriptionClient)
                                {
                                    ClientFactory.DestroySubscription(subscriptionClient.TopicPath, subscriptionClient.SubscriptionName);
                                }

                                controlToken.AttachTask(client.CloseAsync());
                            }
                        }

                        if (LazySendClientDictionary.IsValueCreated)
                        {
                            foreach (var client in SendClientDictionary.Values)
                            {
                                if (client.IsClosedOrClosing)
                                {
                                    continue;
                                }

                                controlToken.AttachTask(client.CloseAsync());
                            }
                        }
                    }

                    ClientFactory.Dispose();
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }
        /// <summary>
        /// Converts the value of the current <see cref="CascadingSymmetricKey" /> to its equivalent binary representation.
        /// </summary>
        /// <returns>
        /// A binary representation of the current <see cref="CascadingSymmetricKey" />.
        /// </returns>
        public SecureBuffer ToBuffer()
        {
            var result = new SecureBuffer(SerializedLength);

            try
            {
                using (var controlToken = StateControl.Enter())
                {
                    result.Access(pinnedResultBuffer =>
                    {
                        var keyLength = SecureSymmetricKey.SerializedLength;

                        for (var i = 0; i < MaximumDepth; i++)
                        {
                            if (i < Depth)
                            {
                                using (var keyBuffer = Keys[i].ToBuffer())
                                {
                                    keyBuffer.Access(pinnedKeyBuffer =>
                                    {
                                        // Copy the key buffers out to the result buffer.
                                        Array.Copy(pinnedKeyBuffer, 0, pinnedResultBuffer, (keyLength * i), keyLength);
                                    });
                                }

                                continue;
                            }

                            // Fill the unused segments with random bytes.
                            var randomBytes = new Byte[keyLength];
                            HardenedRandomNumberGenerator.Instance.GetBytes(randomBytes);
                            Array.Copy(randomBytes, 0, pinnedResultBuffer, (keyLength * i), keyLength);
                        }

                        // Append the depth as a 16-bit integer.
                        Buffer.BlockCopy(BitConverter.GetBytes(Convert.ToUInt16(Depth)), 0, pinnedResultBuffer, (SerializedLength - sizeof(UInt16)), sizeof(UInt16));
                    });

                    return(result);
                }
            }
            catch
            {
                result.Dispose();
                throw new SecurityException("Key serialization failed.");
            }
        }
        /// <summary>
        /// Asynchronously initiates the current <see cref="IDataAccessTransaction" />.
        /// </summary>
        /// <returns>
        /// A task representing the asynchronous operation.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// <see cref="State" /> is not equal to <see cref="DataAccessTransactionState.Ready" />.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public async Task BeginAsync()
        {
            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                if (State == DataAccessTransactionState.Ready)
                {
                    State = DataAccessTransactionState.InProgress;
                    await BeginAsync(controlToken).ConfigureAwait(false);
                }
                else
                {
                    throw new InvalidOperationException($"{nameof(Commit)} cannot be invoked when the transaction state is {State.ToString()}.");
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Writes an element at the tail of the current <see cref="CircularBuffer{T}" />.
        /// </summary>
        /// <param name="element">
        /// The element to write to the buffer.
        /// </param>
        public void Write(T element)
        {
            using (var controlToken = StateControl.Enter())
            {
                ElementArray[WriteIndex] = element;

                if (Length < Capacity)
                {
                    Length++;
                }

                if (++WriteIndex == Capacity)
                {
                    WriteIndex = 0;
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Update the control with delta time. It will pause or restart the <see cref="ParticleSystem"/> if necessary
        /// </summary>
        /// <param name="dt">Delta time elapsed since the last update call</param>
        /// <param name="particleSystem">The <see cref="ParticleSystem"/> which this control should manage</param>
        public void Update(float dt, ParticleSystem particleSystem)
        {
            // Check if state has changed
            if (oldControl != Control)
            {
                switch (Control)
                {
                case StateControl.Play:
                    particleSystem.Play();
                    break;

                case StateControl.Pause:
                    particleSystem.Pause();
                    break;

                case StateControl.Stop:
                    particleSystem.Stop();
                    break;
                }

                oldControl = Control;
            }

            // If the particle system is not currently playing, skip updating the time
            if (Control != StateControl.Play)
            {
                return;
            }

            currentElapsedTime += dt;

            if (resetSeconds <= 0)
            {
                return;
            }

            if (currentElapsedTime >= resetSeconds)
            {
                while (currentElapsedTime >= resetSeconds)
                {
                    currentElapsedTime -= resetSeconds;
                }

                particleSystem.ResetSimulation();
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Simulates a thread-safe operation.
        /// </summary>
        public void SimulateThreadSafeOperation()
        {
            using (var controlToken = StateControl.Enter())
            {
                lock (SyncRoot)
                {
                    ConcurrencyCount++;
                }

                Thread.Sleep(ThreadSafeOperationDelayDuration);

                lock (SyncRoot)
                {
                    ConcurrencyCount--;
                }
            }
        }
        /// <summary>
        /// Commits all changes made within the scope of the current <see cref="DataAccessTransaction" />.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// <see cref="State" /> is not equal to <see cref="DataAccessTransactionState.InProgress" />.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public void Commit()
        {
            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                if (State == DataAccessTransactionState.InProgress)
                {
                    State = DataAccessTransactionState.Committed;
                    Commit(controlToken);
                }
                else
                {
                    throw new InvalidOperationException($"{nameof(Commit)} cannot be invoked when the transaction state is {State.ToString()}.");
                }
            }
        }
        /// <summary>
        /// Converts the value of the current <see cref="SecureSymmetricKey" /> to its equivalent binary representation.
        /// </summary>
        /// <returns>
        /// A binary representation of the current <see cref="SecureSymmetricKey" />.
        /// </returns>
        public SecureBuffer ToBuffer()
        {
            var resultBuffer = new SecureBuffer(SerializedLength);

            try
            {
                using (var controlToken = StateControl.Enter())
                {
                    using (var plaintextBuffer = new PinnedBuffer(SerializedPlaintextLength, true))
                    {
                        KeySource.Access(pinnedKeySourceBuffer =>
                        {
                            Array.Copy(pinnedKeySourceBuffer, 0, plaintextBuffer, KeySourceBufferIndex, KeySourceLengthInBytes);
                        });

                        plaintextBuffer[AlgorithmBufferIndex]      = (Byte)Algorithm;
                        plaintextBuffer[DerivationModeBufferIndex] = (Byte)DerivationMode;

                        using (var cipher = BufferEncryptionAlgorithm.ToCipher(RandomnessProvider))
                        {
                            using (var initializationVector = new PinnedBuffer(cipher.BlockSizeInBytes, true))
                            {
                                RandomnessProvider.GetBytes(initializationVector);

                                resultBuffer.Access(pinnedResultBuffer =>
                                {
                                    using (var ciphertext = cipher.Encrypt(plaintextBuffer, BufferEncryptionKey, initializationVector))
                                    {
                                        Array.Copy(ciphertext, 0, pinnedResultBuffer, 0, SerializedLength);
                                    }
                                });
                            }
                        }
                    }
                }

                return(resultBuffer);
            }
            catch
            {
                resultBuffer.Dispose();
                throw new SecurityException("Key serialization failed.");
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Calculates hash values for the specified ordered data block collection and adds them to the tree.
        /// </summary>
        /// <param name="blocks">
        /// An ordered collection of data block objects to add to the hash tree.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="blocks" /> is <see langword="null" /> -or- <paramref name="blocks" /> contains a null data block object.
        /// </exception>
        /// <exception cref="SecurityException">
        /// An exception was raised during hashing or serialization.
        /// </exception>
        public void AddBlockRange(IEnumerable <TBlock> blocks)
        {
            if (blocks.Any() == false)
            {
                return;
            }

            using (var controlToken = StateControl.Enter())
            {
                var newNodes = blocks.RejectIf().IsNull(nameof(blocks)).TargetArgument.Select(block => CalculateHash(block.RejectIf().IsNull(nameof(blocks)).TargetArgument)).Select(hashValue => new HashTreeNode(hashValue));

                foreach (var node in newNodes)
                {
                    LeafNodes.Add(node);
                }

                PermuteRow(LeafNodes);
            }
        }
        /// <summary>
        /// Gets a shared, managed <see cref="IReceiverClient" /> instance.
        /// </summary>
        /// <typeparam name="TMessage">
        /// The type of the message that the client handles.
        /// </typeparam>
        /// <param name="entityType">
        /// The type of the entity.
        /// </param>
        /// <returns>
        /// The managed <see cref="IReceiverClient" /> instance.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="entityType" /> is equal to <see cref="MessagingEntityType.Unspecified" />.
        /// </exception>
        /// <exception cref="MessageSubscriptionException">
        /// An exception was raised while creating the client.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public IReceiverClient GetReceiveClient <TMessage>(MessagingEntityType entityType)
            where TMessage : class
        {
            var entityPath = GetEntityPath <TMessage>(entityType);

            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                if (ReceiveClientDictionary.TryGetValue(entityPath, out var client))
                {
                    return(client);
                }

                client = ClientFactory.CreateReceiveClient <TMessage>(entityType);
                ReceiveClientDictionary.Add(entityPath, client);
                return(client);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Reads the element at the head of the current <see cref="CircularBuffer{T}" />.
        /// </summary>
        /// <returns>
        /// The element at the head of the buffer.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// The buffer is empty.
        /// </exception>
        public T Read()
        {
            using (var controlToken = StateControl.Enter())
            {
                if (--Length < 0)
                {
                    Length = 0;
                    throw new InvalidOperationException("A read operation failed because the buffer is empty.");
                }

                var element = ElementArray[ReadIndex];

                if (++ReadIndex == Capacity)
                {
                    ReadIndex = 0;
                }

                return element;
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Returns the instance of specified type that is managed by the current <see cref="IFactoryProducedInstanceGroup" />.
        /// </summary>
        /// <typeparam name="T">
        /// The type of the instance to return.
        /// </typeparam>
        /// <returns>
        /// The instance of specified type that is managed by the current <see cref="IFactoryProducedInstanceGroup" />.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// <typeparamref name="T" /> is not a supported type for the group.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        /// <exception cref="ObjectProductionException">
        /// An exception was raised during object production.
        /// </exception>
        public T Get <T>()
            where T : class
        {
            var instanceType = typeof(T);

            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                if (Instances.TryGetValue(instanceType, out var extantInstance))
                {
                    return(extantInstance as T);
                }

                var newInstance = Factory.Produce(instanceType) as T;
                Instances.Add(instanceType, newInstance);
                ReferenceManager.AddObject(newInstance);
                return(newInstance);
            }
        }
Esempio n. 27
0
        private static void collectMetrics(object state)
        {
            StateControl control = state as StateControl;

            if (control.IsRunning)
            {
                return; // skip this run if we're already collecting data
            }
            control.IsRunning = true;

            // restore configured culture setting for this async thread
            Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(conf.DefaultCulture);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(conf.DefaultCulture);

            // gather metrics from all watchers
            List <CollectedMetric> metrics = new List <CollectedMetric>();

            foreach (var watcher in _watchers)
            {
                try
                {
                    watcher.Report(metrics);
                }
                catch (Exception any)
                {
                    Log.Warning("[collectMetrics] Failed to Report on counter watcher for path '{0}'; this report will be skipped for now: {1} (inner: {2})", watcher.MetricPath, any.Message, any.InnerException != null ? any.InnerException.Message : "(null)");
                    continue;
                }
            }

            // transfer metrics over for sending
            foreach (var item in metrics)
            {
                if (!_metricsList.TryAdd(item))
                {
                    Log.Warning("[collectMetrics] Failed to relocate collected metrics to buffer for sending, buffer may be full; increase metric buffer in configuration");
                }
            }

            control.IsRunning = false;
        }
Esempio n. 28
0
        /// <summary>
        /// Decrypts the buffer, performs the specified operation against the pinned plaintext and encrypts the buffer as a
        /// thread-safe, atomic operation.
        /// </summary>
        /// <param name="action">
        /// The operation to perform.
        /// </param>
        /// <exception cref="ObjectDisposedException">
        /// The object is disposed.
        /// </exception>
        public void Access(Action <PinnedBuffer> action)
        {
            using (var controlToken = StateControl.Enter())
            {
                RejectIfDisposed();

                using (var plaintext = new PinnedBuffer(Length, true))
                {
                    DecryptField(plaintext);

                    try
                    {
                        action(plaintext);
                    }
                    finally
                    {
                        EncryptField(plaintext);
                    }
                }
            }
        }
Esempio n. 29
0
 public virtual void Awake()
 {
     this.m_cAni = this.GetComponent <Animation>();
     if (null == this.m_cAni)
     {
         this.m_cAni = this.gameObject.AddComponent <Animation>();
     }
     this.m_cCharacterController = this.GetComponent <CharacterController>();
     if (null == this.m_cCharacterController)
     {
         this.m_cCharacterController = this.gameObject.AddComponent <CharacterController>();
     }
     this.m_cStateControl = new StateControl(this);
     this.m_cStateControl.Idle();
     if (null == this.m_rigidbody)
     {
         this.m_rigidbody             = this.gameObject.AddComponent <Rigidbody>();
         this.m_rigidbody.useGravity  = false;
         this.m_rigidbody.isKinematic = true;
     }
 }
Esempio n. 30
0
    void Update()
    {
        if (StateControl.GetState() != StateType.Playing)
        {
            if (BirdManager.Instance.IsBirdGround)
            {
                if (transform.localPosition.y + _stepY < -502f)
                {
                    transform.localPosition = new Vector3(transform.localPosition.x, -502f, transform.localPosition.z);
                }
            }
            return;
        }

        if (Input.GetMouseButtonDown(0))
        {
            if (!BirdManager.Instance.IsBirdDie)
            {
                AudioManager.Instance.PlayWing();
                _stepY = _distance + Time.deltaTime * _fixedSpeed;
            }
        }
        _stepY -= Time.deltaTime * _fixedSpeed;
        transform.localPosition += new Vector3(0, _stepY, 0);

        Quaternion initial = this.GetComponent <RectTransform>().localRotation;
        Quaternion target;

        if (_stepY >= 0)
        {
            target = Quaternion.Euler(_upRotation);
        }
        else
        {
            target = Quaternion.Euler(_downRotation);
        }
        float rotateSpeed = _stepY >= 0 ? _rotateSpeed : _rotateSpeed * 0.5f;

        this.GetComponent <RectTransform>().localRotation = Quaternion.Lerp(initial, target, rotateSpeed * Time.deltaTime);
    }
Esempio n. 31
0
    protected GfxObject m_cObj; //物体

    #endregion Fields

    #region Constructors

    public CmdStateBase()
    {
        this.m_cControl = this.m_cObj.GetStateControl();
    }
        /// <summary>
        /// Update the control with delta time. It will pause or restart the <see cref="ParticleSystem"/> if necessary
        /// </summary>
        /// <param name="dt">Delta time elapsed since the last update call</param>
        /// <param name="particleSystem">The <see cref="ParticleSystem"/> which this control should manage</param>
        public void Update(float dt, ParticleSystem particleSystem)
        {
            // Check if state has changed
            if (oldControl != Control)
            {
                switch (Control)
                {
                    case StateControl.Play:
                        particleSystem.Play();
                        break;

                    case StateControl.Pause:
                        particleSystem.Pause();
                        break;

                    case StateControl.Stop:
                        particleSystem.Stop();
                        break;
                }

                oldControl = Control;
            }

            // If the particle system is not currently playing, skip updating the time
            if (Control != StateControl.Play)
                return;

            currentElapsedTime += dt;

            if (resetSeconds <= 0)
                return;

            if (currentElapsedTime >= resetSeconds)
            {
                while (currentElapsedTime >= resetSeconds)
                    currentElapsedTime -= resetSeconds;

                particleSystem.ResetSimulation();
            }
        }