Esempio n. 1
0
 public void SetCollision()
 {
     MotionState motionState = new MotionState();
     motionState.Position = Position;
     motionState.Orientation = Quaternion.Identity;
     Entity = new Sphere(motionState, radius, mass);
 }
Esempio n. 2
0
 public void SetCollision()
 {
     var motionState = new MotionState();
     motionState.Position = Position;
     motionState.Orientation = Quaternion.Identity;
     Entity = new Box(motionState, initscale.X, initscale.Y, initscale.Z, mass);
 }
Esempio n. 3
0
		public RigidBody(float mass, MotionState motionState, CollisionShape collisionShape, Vector3 localInertia, float linearDamping, float angularDamping, float friction, float restitution)
		{
			_optionalMotionState = motionState;
			_angularFactor = 1;
			_angularDamping = 0.5f;

			if (motionState != null)
			{
				motionState.GetWorldTransform(out _worldTransform);
			}
			else
			{
				WorldTransform = Matrix.Identity;
			}

			InterpolationWorldTransform = WorldTransform;
			InterpolationLinearVelocity = new Vector3();
			InterpolationAngularVelocity = new Vector3();

			//moved to btCollisionObject
			Friction = friction;
			Restitution = restitution;

			CollisionShape = collisionShape;
			_debugBodyId = UniqueID++;

			//m_internalOwner is to allow upcasting from collision object to rigid body
			Owner = this;

			SetMassProps(mass, localInertia);
			SetDamping(linearDamping, angularDamping);
			UpdateInertiaTensor();
		}
Esempio n. 4
0
 public static MotionState CreateMotionState(Vector3 position, Quaternion orientation, Vector3 velocity)
 {
     MotionState newState = new MotionState();
     newState.Position = position;
     newState.Orientation = orientation;
     newState.LinearVelocity = velocity;
     return newState;
 }
Esempio n. 5
0
    public void SetVelocity(Vector3 velocity)
    {
        this.velocity = velocity;
        bool onGround = motionState == MotionState.ground || motionState == MotionState.crouch;

        if (vertVel > 0f && onGround)
        {
            motionState = MotionState.air;
            platform    = null;
        }
    }
 // Called when Recover Start
 void StartRecover()
 {
     if (CurrentSideLanded == SideLanded.Back)
     {
         CurrentMotionState = MotionState.RecoverBack;
     }
     else
     {
         CurrentMotionState = MotionState.RecoverFront;
     }
 }
Esempio n. 7
0
 // Token: 0x060009A2 RID: 2466 RVA: 0x0004B4E0 File Offset: 0x000496E0
 private void TryInitializeStates()
 {
     foreach (KeyValuePair <Camera, MotionState> keyValuePair in this.m_states)
     {
         MotionState value = keyValuePair.Value;
         if (value.Owner.Initialized && !value.Error && !value.Initialized)
         {
             value.Initialize();
         }
     }
 }
Esempio n. 8
0
    public void SwimState(UFLiquid liquid)
    {
        if (motionState == MotionState.climb || motionState == MotionState.noClip)
        {
            return;
        }

        this.liquid   = liquid;
        motionState   = MotionState.swim;
        this.platform = null;
    }
Esempio n. 9
0
    public void ClimbState(Vector3 climbDirection)
    {
        if (motionState == MotionState.noClip)
        {
            return;
        }

        motionState   = MotionState.climb;
        this.climbDir = climbDirection;
        this.platform = null;
    }
Esempio n. 10
0
 private static void ResetDragState()
 {
     s_CurrentState         = MotionState.kInactive;
     Tools.s_LockedViewTool = ViewTool.None;
     Tools.s_ButtonDown     = -1;
     s_Motion = Vector3.zero;
     if (Toolbar.get)
     {
         Toolbar.get.Repaint();
     }
     EditorGUIUtility.SetWantsMouseJumping(0);
 }
Esempio n. 11
0
 public void Idle(bool needReset = false)
 {
     if (m_motionState == MotionState.Leave)
     {
         return;
     }
     m_motionState = MotionState.Idle;
     if (needReset)
     {
         Reset();
     }
 }
 // 是否能被回旋踢攻击
 protected bool SpinKickAble(Transform player, MotionState enemyState)
 {
     if (enemyState != MotionState.Agonizing)
     {
         return(false);
     }
     if (Vector3.Distance(transform.position, player.position) > PlayerSpinKick.spinKickRadius)
     {
         return(false);
     }
     return(true);
 }
Esempio n. 13
0
    private bool TickThrusters(MotionState state, MotionTarget target)
    {
        Vector3D currentVelocity = state.VelocityLocal;
        Vector3D currentPosition = Vector3D.Transform(state.Position, state.WorldMatrixInverse);
        Vector3D currentGravity  = state.GravityLocal;

        Vector3D targetSpeed    = target.Speed;
        Vector3D targetPosition = Vector3D.Transform(target.Position ?? (state.Position + (targetSpeed + currentVelocity) * DELTA * .66), state.WorldMatrixInverse);

        Vector3D speedDifference    = targetSpeed - currentVelocity;
        Vector3D positionDifference = targetPosition - currentPosition;

        if (speedDifference.LengthSquared() < velocityPrecision && positionDifference.LengthSquared() < positionPrecision)
        {
            ClearThrustersOverride();
            SetDampeners(true);
            return(true);
        }


        Vector3D deceleration       = GetAccelerations(speedDifference) + currentGravity;
        Vector3D decelerationTimes  = speedDifference / deceleration;
        Vector3D positionAtFullStop = currentPosition + currentVelocity * decelerationTimes + deceleration * decelerationTimes * decelerationTimes / 2;

        Vector3D maxAccelerationDelta = targetPosition - positionAtFullStop;
        Vector3D shipAcceleration     = GetAccelerations(maxAccelerationDelta);
        Vector3D acceleration         = shipAcceleration + currentGravity;
        Vector3D accelerationForTick  = (maxAccelerationDelta - currentVelocity * DELTA) / DELTA_SQ_2 - currentGravity;
        Vector3D overrides            = Vector3D.Max(-Vector3D.One, Vector3D.Min(Vector3D.One, 0.5 * accelerationForTick / shipAcceleration)) * 100;

        if (maxAccelerationDelta.X < 0)
        {
            overrides.X = -overrides.X;
        }
        if (maxAccelerationDelta.Y < 0)
        {
            overrides.Y = -overrides.Y;
        }
        if (maxAccelerationDelta.Z < 0)
        {
            overrides.Z = -overrides.Z;
        }

        if (currentVelocity.LengthSquared() >= maxSpeed * maxSpeed && (overrides * currentVelocity).Min() >= -0.01)
        {
            ClearThrustersOverride();
            return(false);
        }

        SetDampeners(decelerationTimes.Max() < DELTA);
        SetThrustersOverride(overrides);
        return(false);
    }
Esempio n. 14
0
 public void SetNoClip(bool value)
 {
     if (value)
     {
         motionState = MotionState.noClip;
     }
     else if (motionState == MotionState.noClip)
     {
         motionState = MotionState.air;
     }
     cc.enabled = !value;
 }
 /// <summary>
 /// Accelerate the specified velocity.
 /// </summary>
 /// <param name="velocity">Reference to current Velocity.</param>
 private void accelerate(ref float velocity)
 {
     if (motionState.Equals(MotionState.accelerating))
     {
         velocity += accel;
         if (velocity >= maxVelocity)
         {
             velocity    = maxVelocity;
             motionState = MotionState.uniformed;
         }
     }
 }
Esempio n. 16
0
        public override void Reset()
        {
            var ms = new MotionState();

            ms.AngularVelocity = MathConverter.Convert(Entity.AngularVelocity);
            ms.LinearVelocity  = MathConverter.Convert(Entity.LinearVelocity);
            ms.Orientation     = MathConverter.Convert(Entity.Rotation);
            ms.Position        = MathConverter.Convert(Entity.Position);
            box.MotionState    = ms;
            box.Orientation    = MathConverter.Convert(Entity.Rotation);
            box.Position       = MathConverter.Convert(Entity.Position);
        }
 /// <summary>
 /// Deaccelerate the specified velocity.
 /// </summary>
 /// <param name="velocity">Velocity.</param>
 private void deaccelerate(ref float velocity)
 {
     if (motionState.Equals(MotionState.deaccelerating))
     {
         velocity += deaccel;
         if (velocity <= 0)
         {
             velocity    = 0;
             motionState = MotionState.stopped;
         }
     }
 }
 /// <summary>
 /// Stops the motion.
 /// </summary>
 /// <returns><c>true</c>, if motion can be stoped (not accelerating nor deaccelerating), <c>false</c> otherwise.</returns>
 public bool stopMotion()
 {
     if (motionState.Equals(MotionState.uniformed))
     {
         this.motionState = MotionState.deaccelerating;
         return(false);
     }
     else
     {
         return(true);
     }
 }
 public MotionPropertiesComponent(GameObject parent, float mass, float maxGroundVelocity, float maxAirVelocity)
     : base(parent)
 {
     this.State = MotionState.Unknown;
     this.MaxGroundSpeed = maxGroundVelocity;
     this.MaxAirSpeed = maxAirVelocity;
     this.Mass = mass;
     this.LastAccelerationVector = Vector2.Zero;
     this.AccelerationVector = Vector2.Zero;
     this._velocityVector = Vector2.Zero;
     this.Impulses = new List<Impulse>();
 }
Esempio n. 20
0
 public Player(Map.Map map) : base()
 {
     drawDepth      = ConfigInfo.PLAYER_DRAW_DEPTH;
     currentState   = MotionState.IDLE_DOWN;
     futureState    = currentState;
     this.map       = map;
     gameNum        = map._gameState._gameNum;
     initPlayerData = InitReader.Read(gameNum);
     Position       = new Vector2(initPlayerData.spawn.X, initPlayerData.spawn.Y);
     graphics       = map._gameState._graphicsDevice;
     playerDir      = $"{map._gameState._gameDir}/player";
     PlayerChunkUpdate();
 }
Esempio n. 21
0
 private void TryInitializeStates()
 {
     Dictionary <Camera, MotionState> .Enumerator enumerator = this.m_states.GetEnumerator();
     while (enumerator.MoveNext())
     {
         KeyValuePair <Camera, MotionState> current = enumerator.Current;
         MotionState value = current.Value;
         if (value.Owner.Initialized && !value.Error && !value.Initialized)
         {
             value.Initialize();
         }
     }
 }
Esempio n. 22
0
        public MotionState GetMotionState <T>(T[] objects, MotionState previous_state, float sensitivity = 0.1f)
            where T : IMotionTracker
        {
            foreach (var o in objects)
            {
                if (o.IsInMotion(sensitivity))
                {
                    return(MotionState.Is_moving_);
                }
            }

            return(previous_state != MotionState.Is_moving_ ? MotionState.Is_at_rest_ : MotionState.Was_moving_);
        }
        /// <summary>
        /// Update Agent's position and animation on the way to a target position.
        /// </summary>
        /// <param name="targetTransform"></param>
        /// <param name="moveSpeed"></param>
        /// <param name="motionState"></param>
        /// <param name="animationState"></param>
        /// <param name="animationFadeSpeed"></param>
        /// <param name="energyCost"></param>
        /// <param name="actionOnNotEnoughEnergy"></param>
        /// <param name="updateTimeVariable"></param>
        /// <param name="stopAction"></param>
        private void MoveTowards(Transform targetTransform, float moveSpeed, MotionState motionState, AnimationState animationState,
                                 float animationFadeSpeed, int energyCost, Action actionOnNotEnoughEnergy, ref float updateTimeVariable,
                                 Action stopAction)
        {
            Vector3?targetPosition = null;

            if (targetTransform)
            {
                targetPosition = targetTransform.position;
            }
            MoveTowards(targetPosition, moveSpeed, motionState, animationState,
                        animationFadeSpeed, energyCost, actionOnNotEnoughEnergy, ref updateTimeVariable, stopAction);
        }
        void Update()
        {
            MotionState state = playerMotionController.CurrentMotionState;

            if (state == MotionState.Idling || state == MotionState.Moving || state == MotionState.Attacking)
            {
                isIKActive = true;
            }
            else
            {
                isIKActive = false;
            }
        }
Esempio n. 25
0
        //moves a set amount per frame toward a certain location
        public override void Move(Microsoft.Xna.Framework.Vector2 loc, TimeSpan elapsedTime)
        {
            //should really just use the Sim's position for everything instead of converting from one to another
            Vector2 simPosition = ConvertUnits.ToDisplayUnits(_circleBody.Position);

            if (float.IsNaN(simPosition.X) || float.IsNaN(simPosition.Y))
            {
                return;
            }
            else
            {
                this.Position = simPosition;
            }
            switch (m_State)
            {
            case MotionState.Wandering:
                if (RANDOM_GENERATOR.Next(150) % 150 == 1)
                {
                    RotationAngle = (float)RANDOM_GENERATOR.NextDouble() * MathHelper.Pi * 2;
                    m_Direction.X = (float)Math.Cos(RotationAngle);
                    m_Direction.Y = (float)Math.Sin(RotationAngle);
                }
                break;

            case MotionState.Locked:
                m_Direction   = loc;
                RotationAngle = (float)Math.Atan2(loc.Y, loc.X);
                m_State       = MotionState.Locked;
                m_Speed       = 2.0f;
                break;
            }

            m_Direction = Vector2.Normalize(m_Direction);
            Vector2 amount = m_Direction * m_Speed;

            base.Move(amount, elapsedTime);

            //Later on, remove the clamp to the edge and despawn when too far out of the screen.
            //Vector2 temp = new Vector2();
            //temp.X = MathHelper.Clamp(Position.X, Width + UI.OFFSET, Game1.GameWidth - (Width / 2));
            //temp.Y = MathHelper.Clamp(Position.Y, Height, Game1.GameHeight - (Height / 2));
            //Position = temp;
            if (!float.IsNaN(this.Position.X) && !float.IsNaN(this.Position.Y))
            {
                _circleBody.Position = ConvertUnits.ToSimUnits(this.Position);
            }

            m_Bounds.X = (int)Position.X - Width / 2;
            m_Bounds.Y = (int)Position.Y - Height / 2;
        }
 /// <summary>
 /// Stand still idling, with different animation from idle one.
 /// </summary>
 public void Stand()
 {
     if (_locked)
     {
         return;
     }
     State = MotionState.Standing;
     _motion.Animate(AnimationState.Idling);
     SetSpeed(0);
     if (_agent.Target != _transform)
     {
         _agent.Target = _transform;
     }
 }
 /// <summary>
 /// Stand and relax playing default animation.
 /// </summary>
 public void Idle()
 {
     if (_locked)
     {
         return;
     }
     State = MotionState.Idling;
     _motion.Animate(AnimationState.Idling);
     SetSpeed(0);
     if (_motion.Target != _transform.position)
     {
         _motion.Target = _transform.position;
     }
 }
Esempio n. 28
0
    private bool G1(MotionState s, MotionTarget t)
    {
        var a = Quaternion.Inverse(t.Rotation.Value); var b = s.Orientation; var d = Math.Abs(b.X - a.X) + Math.Abs(b.Y - a.Y) + Math.Abs(b.Z - a.Z) + Math.Abs(b.W - a.W); SG(true); bool h = d < angularPrecision && s.AngularVelocityLocalYPR.LengthSquared() < angularPrecision; HG(h); if (h)

        {
            return(true);
        }
        foreach (var g in G)
        {
            var c = CG(g, a); var w = MatrixD.Invert(g.WorldMatrix); var x = Vector3D.TransformNormal(s.AngularVelocityWorldYPR, w); var y = c * angularCorrectionFactor;
            var z = y - s.AngularVelocityLocalYPR * rotationDampening; g.SetValueFloat("Yaw", -(float)z.Y); g.SetValueFloat("Pitch", (float)z.X); g.SetValueFloat("Roll", -(float)z.Z);
        }
        return(false);
    }
Esempio n. 29
0
    // Attackステートに遷移します
    private void SetAttackState()
    {
        motionState = MotionState.Attack;
        ChangeAnimation(AnimationPattern.Attack);

        // 移動を止めます
        var velocity = rigidbody2D.velocity;

        velocity             = Vector3.zero;
        rigidbody2D.velocity = velocity;

        // 攻撃の演出を開始します
        StartCoroutine(OnAttack());
    }
Esempio n. 30
0
 private void SetState(MotionState s)
 {
     if (availableStates.ContainsKey(s))
     {
         if (availableStates[s].CanStart())
         {
             StartCoroutine(TransitionToState(s));
         }
     }
     else
     {
         Debug.LogWarningFormat("No motion availble for state {0}", s);
     }
 }
Esempio n. 31
0
    public MotionState[] ReadRokokoData(string path)
    {
        Quaternion[] rotations = new Quaternion[24];

        string[]      everyLine = File.ReadAllLines(path);
        MotionState[] mST       = new MotionState[everyLine.Length - 1];
        Debug.Log(everyLine.Length);
        for (int i = 1; i < everyLine.Length; i++)
        {
            string[] splitLine = everyLine[i].Split(',');
            //Debug.Log(splitLine.Length);

            /* for (int j = 4; j < splitLine.Length; j += 7)
             * {
             *  rotations[(j - 4) / 7] = new Quaternion(float.Parse(splitLine[j]), float.Parse(splitLine[j + 1]), float.Parse(splitLine[j + 2]), float.Parse(splitLine[j + 3]));
             * } */
            for (int j = 0, k = 0; j < rotations.Length; j++)
            {
                if (j == 6 || j == 10)
                {
                    k += 7;
                }
                int alma = 7 * j + 4 + k;

                /* Debug.Log("j: " + j + " motionID: " + alma);
                *  alma++;
                *  Debug.Log("j: " + j + " motionID: " + alma);
                *  alma++;
                *  Debug.Log("j: " + j + " motionID: " + alma);
                *  alma++;
                *  Debug.Log("j: " + j + " motionID: " + alma); */
                rotations[j] = new Quaternion(float.Parse(splitLine[7 * j + 4 + k]), float.Parse(splitLine[7 * j + 5 + k]), float.Parse(splitLine[7 * j + 6 + k]), float.Parse(splitLine[7 * j + 7 + k]));
            }
            mST[i - 1] = new MotionState(rotations);
        }

        rokokoHeaders = new string[rotations.Length];
        string[] tempHeader = everyLine[0].Split(',');
        for (int i = 0, j = 0; i < rokokoHeaders.Length; i++)
        {
            if (i == 6 || i == 10)
            {
                j += 7;
            }
            rokokoHeaders[i] = tempHeader[i * 7 + 4 + j].Split('_')[0];
        }

        return(mST);
    }
Esempio n. 32
0
    //同步玩家信息,使用影子跟随算法
    //该函数调用大约以每秒5次的频率调用,在这里看看是否有别的优化方案
    public void SyncMotionState(ProtocolBase proto)
    {
        int           start     = 0;
        ProtocolBytes protocol  = (ProtocolBytes)proto;
        string        protoName = protocol.GetString(start, ref start);

        if (protoName != "SyncMotionState")
        {
            return;
        }
        string player_id = protocol.GetString(start, ref start);

        float pos_x = protocol.GetFloat(start, ref start);
        float pos_y = protocol.GetFloat(start, ref start);
        float pos_z = protocol.GetFloat(start, ref start);
        float rot_x = protocol.GetFloat(start, ref start);
        float rot_y = protocol.GetFloat(start, ref start);
        float rot_z = protocol.GetFloat(start, ref start);
        float vel_x = protocol.GetFloat(start, ref start);
        float vel_y = protocol.GetFloat(start, ref start);
        float vel_z = protocol.GetFloat(start, ref start);

        //同步位置、转向
        Vector3 _position = new Vector3(pos_x, pos_y, pos_z);
        Vector3 _rotation = new Vector3(rot_x, rot_y, rot_z);
        Vector3 _velocity = new Vector3(vel_x, vel_y, vel_z);

        //根据id去更新PlayerController的信息
        Debug.Log("SyncMotionState " + player_id);
        if (!m_playerControllerList.ContainsKey(player_id))
        {
            Debug.Log("SyncMotionState pc == null ");
            return;
        }
        PlayerController pc = m_playerControllerList[player_id];

        if (player_id == GameMgr.instance.local_player_ID)//本地玩家的同步信息省略
        {
            return;
        }

        MotionState recv_state = new MotionState();

        recv_state.position = _position;
        recv_state.rotation = _rotation;
        recv_state.velocity = _velocity;

        pc.RecvMotionState(recv_state);
    }
 static void TemporaryTool(ViewTool tool)
 {
     Tools.s_LockedViewTool = Tools.viewTool = tool;
     s_CurrentState         = MotionState.kDragging;
     HandleMouseDown(SceneView.lastActiveSceneView, s_ViewToolID, Event.current?.button ?? 0);
     UpdateViewToolState(Event.current);
     if (Event.current != null)
     {
         shortcutKey = Event.current.isMouse ? KeyCode.Mouse0 + Event.current.button : Event.current.keyCode;
     }
     else
     {
         shortcutKey = KeyCode.None;
     }
 }
Esempio n. 34
0
        public override void Update(Player player, TimeSpan elapsedTime)
        {
            //get a normalized direction toward the point that was passed in, probably the player
            Vector2 vec = new Vector2(player.Position.X - Position.X, player.Position.Y - Position.Y);

            if (vec.LengthSquared() <= (275.0f * 275.0f))
            {
                m_State = MotionState.Locked;
            }
            ObjectManager.GetCell(Position).Remove(this);
            Move(vec, elapsedTime);
            ObjectManager.GetCell(Position).Add(this);

            bodyPosition = _circleBody.Position;
        }
Esempio n. 35
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="game"></param>
		/// <param name="space"></param>
		public RigidBody ( Entity entity, World world, float w, float h, float d, float mass ) : base(entity,world)
		{
			this.space	=	((MPWorld)world).PhysSpace;

			var ms	=	new MotionState();
			ms.AngularVelocity	=	MathConverter.Convert( entity.AngularVelocity );
			ms.LinearVelocity	=	MathConverter.Convert( entity.LinearVelocity );
			ms.Orientation		=	MathConverter.Convert( entity.Rotation );
			ms.Position			=	MathConverter.Convert( entity.Position );
			box	=	new Box(  ms, w, h, d, mass );
			box.PositionUpdateMode	=	PositionUpdateMode.Continuous;

			box.Tag	=	entity;

			space.Add( box );
		}
Esempio n. 36
0
        private void button_solveOrbitParam_Click(object sender, EventArgs e)
        {
            XYZ         pos   = XYZ.Parse(this.textBox_pos.Text);
            XYZ         vel   = XYZ.Parse(this.textBox_vel.Text);
            MotionState state = new MotionState(pos, vel);
            CelestialMomentEllipseOrbit orbit = new CelestialMomentEllipseOrbit(state);

            textBox_a.Text          = orbit.MomentEllipseOrbit.PlaneEllipse.a + "";
            this.textBox_e.Text     = orbit.MomentEllipseOrbit.PlaneEllipse.e + "";
            this.textBox_i.Text     = orbit.Inclination + "";
            this.textBox_M.Text     = orbit.MomentEllipseOrbit.MeanAnomaly + "";
            this.textBox_Ω.Text     = orbit.RightAscensionOfAscendingNode + "";
            this.textBox_omiga.Text = orbit.ArgumentOfPerigee + "";

            MessageBox.Show("轨道参数已更新!");
        }
Esempio n. 37
0
        internal void Enable()
        {
            //Turn everything on.
            lock (FlipLocker)
            {

                int initialCount = Math.Max(manager.entities.Count, 64);
                backBuffer = new MotionState[initialCount];
                frontBuffer = new MotionState[initialCount];
                for (int i = 0; i < manager.entities.Count; i++)
                {
                    Entity entity = manager.entities[i];
                    backBuffer[i].Position = entity.position;
                    backBuffer[i].Orientation = entity.orientation;
                    backBuffer[i].LinearVelocity = entity.linearVelocity;
                    backBuffer[i].AngularVelocity = entity.angularVelocity;
                }
                Array.Copy(backBuffer, frontBuffer, backBuffer.Length);
            }
        }
Esempio n. 38
0
    protected override void OnUpdate( FingerGestures.IFingerList touches )
    {
        if( Finger.IsDown )
        {
            if( !wasDown )
            {
                Moves = 0;
                AnchorPos = Finger.Position;
                State = MotionState.Stationary;
            }

            if( Finger.Phase == FingerGestures.FingerPhase.Moved )
            {
                if( State != MotionState.Moving )
                {
                    Vector2 delta = Finger.Position - AnchorPos;

                    // check if we moved beyond the threshold
                    if( delta.sqrMagnitude >= MoveThreshold * MoveThreshold )
                        State = MotionState.Moving;
                    else
                        State = MotionState.Stationary;
                }
            }
            else
            {
                State = MotionState.Stationary;
            }
        }
        else
        {
            State = MotionState.None;
        }

        RaiseEvents();

        PreviousState = State;
        wasDown = Finger.IsDown;
    }
Esempio n. 39
0
 ///<summary>
 /// Gets the states of all entities atomically.
 ///</summary>
 ///<param name="states">Entity states.</param>
 ///<exception cref="InvalidOperationException">Thrown when the array is too small.</exception>
 public void GetStates(MotionState[] states)
 {
     lock (FlipLocker)
     {
         if (states.Length < manager.entities.Count)
         {
             throw new ArgumentException("Array is not large enough to hold the buffer.", "states");
         }
         Array.Copy(frontBuffer, states, manager.entities.Count);
     }
 }
Esempio n. 40
0
        internal void Add(Entity e)
        {

            //Don't need to lock since the parent manager handles it.
            if (frontBuffer.Length <= e.BufferedStates.motionStateIndex)
            {
                var newStates = new MotionState[frontBuffer.Length * 2]; //TODO: shifty
                frontBuffer.CopyTo(newStates, 0);
                frontBuffer = newStates;
            }
            frontBuffer[e.BufferedStates.motionStateIndex].Position = e.position;
            frontBuffer[e.BufferedStates.motionStateIndex].Orientation = e.orientation;

            if (backBuffer.Length <= e.BufferedStates.motionStateIndex)
            {
                var newStates = new MotionState[backBuffer.Length * 2]; //TODO: shifty
                backBuffer.CopyTo(newStates, 0);
                backBuffer = newStates;
            }
            backBuffer[e.BufferedStates.motionStateIndex].Position = e.position;
            backBuffer[e.BufferedStates.motionStateIndex].Orientation = e.orientation;
        }
Esempio n. 41
0
 public static MotionState CreateMotionState(Vector3 position, Quaternion orientation)
 {
     MotionState newState = new MotionState();
     newState.Position = position;
     newState.Orientation = orientation;
     return newState;
 }
Esempio n. 42
0
        public override void PrepareForIteration(float timestep)
        {
            RigidBody body;
            float depth;

            bool collidesWithLadder = world.CollisionSystem.Raycast(Body1.Position + JVector.Forward * (FeetPosition - 0.1f),
                new JVector(0, 1, 0),
                (b, n, f) => b != Body1 && (b.BroadphaseTag & (int)BodyTags.Ghost) == 0,
                out body, out normal, out depth);
            bool collidesWithGround = world.CollisionSystem.Raycast(Body1.Position + new JVector(0, 0.5f, 0) + JVector.Forward * (FeetPosition - 0.1f),
                JVector.Forward,
                (b, n, f) => b != Body1 && (b.BroadphaseTag & (int)BodyTags.Ghost) == 0,
                out body, out normal, out depth);
            BodyWalkingOn = ((!collidesWithGround || depth > 0.2f) ? null : body);
            var oldState = State;
            switch (oldState)
            {
                case MotionState.Grounded:
                    if (BodyWalkingOn != null)
                    {
                        if (tryClimb)
                        {
                            State = MotionState.Climbing;
                            tryClimb = false;
                        }
                        else if (Body1.LinearVelocity.Z < JumpVelocity && tryJump) State = MotionState.Jumping;
                    }
                    else if (-Body1.LinearVelocity.Z < FallVelocity) State = MotionState.Falling;
                    break;
                case MotionState.Jumping:
                    if (-Body1.LinearVelocity.Z < FallVelocity) State = MotionState.Falling;
                    else if (depth < 0.1f && Body1.LinearVelocity.Z < 0.0f) State = MotionState.Grounded;
                    break;
                case MotionState.Falling:
                    if (BodyWalkingOn != null && depth < 0.1f && Body1.LinearVelocity.Z < 0.0f) State = MotionState.Grounded;
                    break;
                case MotionState.Climbing:
                    if (BodyWalkingOn == null && !collidesWithLadder)
                        State = MotionState.Grounded;
                    break;
            }
            if (State != oldState)
            {
                if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(oldState, State));
                Log.WriteLine(LogLevel.Debug, "switched from {0} to {1}", oldState, State);
            }
        }
Esempio n. 43
0
 public StateChangeEventArgs(MotionState oldState, MotionState state)
 {
     Previous = oldState;
     Current = state;
 }