예제 #1
0
파일: Player.cs 프로젝트: Boerlam001/Pong
        public void HandleInput(GameTime gameTime)
        {
            currentTime += (float)gameTime.ElapsedGameTime.Milliseconds;

            KeyboardState keys = Keyboard.GetState();

            if (keys.IsKeyDown(Keys.Up))
            {
                float x = (float)Math.Sin(facing);
                float z = (float)Math.Cos(facing);

                JVector newPath = new JVector(x, 0f, z) * speed;
                newPath = newPath * currentTime;
                newPath.Normalize();

                forward = newPath;

                body.AddForce(newPath * 100f);
                //position = body.Position;
                //position += newPath;

                //body.Position = position;
            }

            if (keys.IsKeyDown(Keys.Left))
            {
                facing -= 0.05f;
            }

            if (keys.IsKeyDown(Keys.Right))
            {
                facing += 0.05f;
            }

            if (keys.IsKeyDown(Keys.Down))
            {
                float x = (float)Math.Sin(facing);
                float z = (float)Math.Cos(facing);

                JVector newPath = new JVector(x, 0f, z) * speed;
                newPath = newPath * currentTime;
                newPath.Normalize();

                body.AddForce(newPath * -100f);
            }

            if (keys.IsKeyDown(Keys.Space))
            {
                body.AddForce(JVector.Up * 100f);
            }

            /*if (keys.IsKeyDown(Keys.A))
             *
             * if (keys.IsKeyDown(Keys.S))
             *
             * if (keys.IsKeyDown(Keys.W))
             */
        }
예제 #2
0
        private void AddBlowerForceToNearbyRigid(RigidBody rigid)
        {
            Vector3 force = new Vector3(StaticData.BlowerForceOnRigid, 0, 0);

            switch (Dir)
            {
            case Direction.East:
                // Initialized
                break;

            case Direction.South:
                force.Y = -force.X;
                force.X = 0;
                break;

            case Direction.West:
                force.X = -force.X;
                break;

            case Direction.North:
                force.Y = force.X;
                force.X = 0;
                break;

            default:
                //Nothing
                break;
            }
            rigid.AddForce(force * rigid.Mass);
        }
    public virtual void Damage(Transform source, float damage, float stunTime, float knockback, float knockbackHeight = 0)
    {
        Health -= damage;

        var dir = (transform.position - source.position);

        dir.y = knockbackHeight;
        dir.Normalize();

        MusicManager.Instance.PlaySound(HitSounds[UnityEngine.Random.Range(0, HitSounds.Length)], 0.9f);

        if (IsDead())
        {
            Invoke("Kill", 1.2f);

            RigidBody.AddForce(dir * knockback * 50, ForceMode.Impulse);
            GameManager.Instance.Hitstun(1);

            GameManager.Instance.Player1.PlayerCamera.Shake(1, 0.7f);
            GameManager.Instance.Player2.PlayerCamera.Shake(1, 0.7f);
            return;
        }

        if (stunTime > 0)
        {
            GameManager.Instance.Hitstun(stunTime);
        }

        RigidBody.AddForce(dir * knockback * 25, ForceMode.Impulse);
    }
예제 #4
0
 public void Boost()
 {
     if (State == BirdState.Thrown && !_hasBoost)
     {
         RigidBody.AddForce(RigidBody.velocity * _boostForce);
         _hasBoost = true;
     }
 }
예제 #5
0
파일: Cue.cs 프로젝트: rumkugel13/EightBall
        public override void OnUpdate(float elapsedSeconds)
        {
            base.OnUpdate(elapsedSeconds);

            if (!this.poweringUp)
            {
                if (Kadro.Input.KeyboardInput.IsKeyDown(Keys.Left))
                {
                    this.Transform.Rotation -= this.resolutionsPerSecond * elapsedSeconds;
                    this.Transform.Position  = VectorExtensions.Rotate(this.Transform.Position, -this.resolutionsPerSecond * elapsedSeconds, focusPosition - offset);
                }

                if (Kadro.Input.KeyboardInput.IsKeyDown(Keys.Right))
                {
                    this.Transform.Rotation += this.resolutionsPerSecond * elapsedSeconds;
                    this.Transform.Position  = VectorExtensions.Rotate(this.Transform.Position, this.resolutionsPerSecond * elapsedSeconds, focusPosition - offset);
                }

                if (MouseInput.OnMouseMoved())
                {
                    float targetAngle = (GameScene.ActiveScene.ViewToWorld(MouseInput.PositionVector) - focusPosition + offset).PerpRight().ToPolar();
                    //targetAngle = MathExtensions.LerpAngle(this.Transform.Rotation, targetAngle, 1.0f * elapsedSeconds);
                    this.Transform.Rotation = targetAngle;
                    this.Transform.Position = VectorExtensions.Rotate(focusPosition, targetAngle, focusPosition - offset);
                }

                if (Kadro.Input.KeyboardInput.OnKeyDown(Keys.Space))
                {
                    this.poweringUp = true;

                    // add constant velocity to move back
                    RigidBody r = this.Components.Get <RigidBodyComponent>().RigidBody;
                    r.AddVelocityChange(VectorExtensions.AngleToVector2(this.Transform.Rotation).PerpLeft() * this.poweringUpVelocity * elapsedSeconds);
                }
            }

            if (this.poweringUp && Kadro.Input.KeyboardInput.IsKeyDown(Keys.Space))
            {
                this.timeSinceStart += elapsedSeconds;
            }

            if ((this.poweringUp && Kadro.Input.KeyboardInput.OnKeyUp(Keys.Space)) || this.timeSinceStart > this.releaseTime)
            {
                // release
                this.timeSinceStart = 0f;
                this.releasing      = true;
                RigidBody r = this.Components.Get <RigidBodyComponent>().RigidBody;
                r.Velocity        = Vector2.Zero;
                r.AngularVelocity = 0;
            }

            if (this.releasing)
            {
                // accelerate cue until it hits the ball
                RigidBody r = this.Components.Get <RigidBodyComponent>().RigidBody;
                r.AddForce(-VectorExtensions.AngleToVector2(this.Transform.Rotation).PerpLeft() * this.releaseForce * elapsedSeconds);
            }
        }
예제 #6
0
 public void TakeDamage(float damage)
 {
     SpriteRenderer.material.color = new Color32(255, 180, 180, 255);
     StartCoroutine(NormalizeColor());
     RigidBody.AddForce(transform.right * 0.01f, ForceMode2D.Impulse); // TODO Remove hardcode
     Animator.SetFloat(AnimatorSpeedParameterName, 0);
     Animator.SetTrigger(AnimatorReceiveDamageTriggerName);
     Enemy.TakeDamage(damage);
 }
 // Use this for initialization
 void Start(int range)
 {
     //When created, the hook will rotate back and fire a certain distance. It's not effected by gravity, so it'll
     //go in a straigh line.
     physics = GetComponent <RigidBody>;
     transform.Rotate(new Vector3(0, -45, 0));
     physics.AddForce(new Vector3(0, 0, 10 + 10 * range));
     flying = false;
 }
예제 #8
0
 public override void Jump()
 {
     if (!CheckGrounded())
     {
         return;
     }
     Animator.SetTrigger("Jump");
     PlaySound(jump);
     RigidBody.AddForce(Vector2.up * JumpForce);
 }
예제 #9
0
        ///<summary>
        /// Applies the gravitational force to the given rigid body.
        ///</summary>
        public override void UpdateForce(RigidBody body, double dt)
        {
            // Check that we do not have infinite mass
            if (body.HasInfiniteMass)
            {
                return;
            }

            // Apply the mass-scaled force to the body
            body.AddForce(m_gravity * body.GetMass());
        }
예제 #10
0
        public virtual void Update(GameTime gameTime)
        {
            Cell cellat = area.CellAt(Position);

            if (cellat != null && Position.Y < area.WaterHeight && cellat.isLake)
            {
                JVector d = area.Physics.Gravity * -1;
                d.Normalize();
                RigidBody.AddForce(d * (RigidBody.Mass * Bouyancy * area.Physics.Gravity.Length()));
            }
        }
    private void FollowEat()
    {
        Vector3 playerPosition = _player.transform.position;

        forceVector = playerPosition - transform.position;
        forceVector = forceVector.normalized * force;

        RigidBody.AddForce(forceVector);
        RigidBody.velocity *= _forceFade;

        transform.LookAt(_player.transform);
    }
예제 #12
0
 void HandleMovement()
 {
     if (RigidBody.velocity.y < 0 && !Dead)
     {
         animator.SetBool("Land", true);
     }
     if (Jump && RigidBody.velocity.y == 0 && !Dead)
     {
         RigidBody.AddForce(new Vector2(0, jumpForce));
     }
     //  if (GameController.instance.scrollSpeed >0)
     animator.SetFloat("Speed", 1.0f);
 }
예제 #13
0
 void FixedUpdate()
 {
     //Can just use the straight reference to the script rather
     //then update a bool every frame
     //Also switched to Fire1 in case user is using a controller
     if (pickUpBallScript.holding && Input.GetKey("Fire1"))
     {
         strength += increaseRate;
         aaRb.AddForce(strength, 0, 0);
         //Removed the instantiate as that is quite heavy on the
         //engine and will quickly cause performance issues
     }
 }
예제 #14
0
    // Update is called once per frame
    void Update()
    {
        OldPosition = positionOfParent.transform.position.x;

        if (Input.GetKeyDown("space") && !shooting)
        {
            // Set shooting to true
            shooting = true;

            // The Bullet instantiation, to make a copy whenever firing
            GameObject Bullet_Handler;
            Bullet_Handler = Instantiate(Bullet, Bullet_Spawn_Point.transform.position, Bullet_Spawn_Point.transform.rotation);

            // Sometimes bullets may appear rotated incorrectly due to the way its pivot was set from the original, can be corrected here
            Bullet_Handler.transform.Rotate(Vector3.forward * 90);

            // Retrieve the Rigidbody2D component from the instantiated Bullet and control it.
            Rigidbody2D RigidBody;
            RigidBody = Bullet_Handler.GetComponent <Rigidbody2D>();

            // If the old position is greater or equal to the current, the bullet will be going right
            if (OldPosition >= positionOfParent.transform.position.x)
            {
                // Tell the bullet to be "pushed" forward by an amount set by Bullet_Forward_Force.
                RigidBody.AddForce(transform.right * Bullet_Force);
            }
            // Else we have to send it left because we are facing the opposite direction
            else
            {
                RigidBody.AddForce(transform.right * -(Bullet_Force));
            }

            // Set the Bullets to self destruct after 3 Seconds
            Destroy(Bullet_Handler, 3.0f);
        }
        if (shooting)
        {
            // If already shooting start timer until it reaches proper delay time
            bullet_Timer += Time.deltaTime;
            if (bullet_Timer >= bullet_Delay)
            {
                // Reset timer and set shooting to false to start the process over and allow more shooting
                bullet_Timer = 0f;
                shooting     = false;
            }
        }
    }
예제 #15
0
    /**
     * Applies the jump effect to the player
     *@param axis - translation axis, defined by the user inputs
     */
    void Jump(Vector2 axis)
    {
        // is body currently lying on the ground?
        if (IsGrounded)
        {
            RigidBody.drag = 5.0f;

            // not already jumping?
            if (m_Jump)
            {
                Jumping = true;

                // apply the jump force
                RigidBody.drag     = 0.0f;
                RigidBody.velocity = new Vector3(RigidBody.velocity.x, 0.0f, RigidBody.velocity.z);
                RigidBody.AddForce(new Vector3(0.0f, m_TranslationController.m_JumpForce, 0.0f), ForceMode.Impulse);

                // run the jump animation
                if (m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_DoKick)
                {
                    m_ModelController.AnimState = IModelController.IEAnimState.IE_AS_Jumping;
                }
            }

            // mitigate the jump effect when the player lies again on the ground, and if he isn't running
            if (!Jumping && Mathf.Abs(axis.x) < float.Epsilon && Mathf.Abs(axis.y) < float.Epsilon && RigidBody.velocity.magnitude < 1.0f)
            {
                RigidBody.Sleep();
            }
        }
        else
        {
            RigidBody.drag = 0.0f;

            // if not jumping, check if the player is falling down a slope
            if (m_PreviouslyGrounded && !Jumping)
            {
                StickToGround();
            }
        }

        m_Jump = false;
    }
예제 #16
0
        private void BuildScene()
        {
            // creating two boxShapes with different sizes
            Shape boxShape    = new BoxShape(JVector.One);
            Shape groundShape = new BoxShape(new JVector(10, 1, 10));

            // create new instances of the rigid body class and pass
            // the boxShapes to them
            RigidBody boxBody1 = new RigidBody(boxShape);
            RigidBody boxBody2 = new RigidBody(boxShape);

            boxBody1.Tag = Color.LightPink;
            boxBody2.Tag = Color.LightSkyBlue;

            RigidBody groundBody = new RigidBody(groundShape);

            groundBody.Tag = Color.LightGreen;

            // set the position of the box size=(1,1,1)
            // 2 and 5 units above the ground box size=(10,1,10)
            boxBody1.Position = new JVector(0, 4, 1.0f);
            boxBody2.Position = new JVector(0, 4, -1.0f);

            pointConstraint = new PointConstraint(
                boxBody1, boxBody2, new JVector(0, 4f, 0));

            // add a force to one body - so it's not that boring
            boxBody1.AddForce(JVector.One * 10);

            world.AddConstraint(pointConstraint);

            // make the body static, so it can't be moved
            groundBody.IsStatic = true;

            // add the bodies to the world.
            world.AddBody(boxBody1);
            world.AddBody(boxBody2);
            world.AddBody(groundBody);
        }
예제 #17
0
        public void PreStep(float timeStep)
        {
            float vel = car.LinearVelocity.Length();

            SideFriction    = 2.5f - JMath.Clamp(vel / 20.0f, 0.0f, 1.4f);
            ForwardFriction = 5.5f - JMath.Clamp(vel / 20.0f, 0.0f, 5.4f);

            JVector force = JVector.Zero;

            JVector worldAxis = JVector.Transform(JVector.Up, car.Orientation);
            JVector worldPos  = car.Position + JVector.Transform(Position, car.Orientation);

            JVector forward = new JVector(-car.Orientation.M31, -car.Orientation.M32, -car.Orientation.M33);

            JVector wheelFwd  = JVector.Transform(forward, JMatrix.CreateFromAxisAngle(JVector.Up, SteerAngle / 360 * 2 * JMath.Pi));
            JVector wheelLeft = JVector.Cross(JVector.Up, wheelFwd); wheelLeft.Normalize();
            JVector wheelUp   = JVector.Cross(wheelFwd, wheelLeft);

            float rayLen = 2.0f * Radius + WheelTravel;

            JVector wheelRayStart = worldPos;
            JVector wheelDelta    = -Radius * worldAxis;
            JVector wheelRayEnd   = worldPos + wheelDelta;

            float deltaFwd      = (2.0f * Radius) / (NumberOfRays + 1);
            float deltaFwdStart = deltaFwd;

            lastDisplacement = displacement;
            displacement     = 0.0f;

            lastOnFloor = false;

            JVector rayOrigin = car.Position + JVector.Transform(Position, car.Orientation);

            JVector   groundNormal = JVector.Zero;
            JVector   groundPos    = JVector.Zero;
            float     deepestFrac  = float.MaxValue;
            RigidBody worldBody    = null;

            for (int i = 0; i < NumberOfRays; i++)
            {
                float distFwd = (deltaFwdStart + i * deltaFwd) - Radius;
                float zOffset = Radius * (1.0f - (float)Math.Cos(Math.PI / 4 * (distFwd / Radius)));

                JVector newOrigin = wheelRayStart + distFwd * wheelFwd + zOffset * wheelUp;

                RigidBody body; JVector normal; float frac;
                bool      result = world.CollisionSystem.Raycast(newOrigin, wheelDelta,
                                                                 raycast, out body, out normal, out frac);



                if (result && frac <= 1.0f)
                {
                    if (frac < deepestFrac)
                    {
                        deepestFrac  = frac;
                        groundPos    = rayOrigin + frac * wheelDelta;
                        worldBody    = body;
                        groundNormal = normal;
                    }

                    lastOnFloor = true;
                }
            }

            if (!lastOnFloor)
            {
                return;
            }

            if (groundNormal.LengthSquared() > 0.0f)
            {
                groundNormal.Normalize();
            }

            // System.Diagnostics.Debug.WriteLine(groundPos.ToString());


            displacement = rayLen * (1.0f - deepestFrac);
            displacement = JMath.Clamp(displacement, 0.0f, WheelTravel);

            float displacementForceMag = displacement * Spring;

            // reduce force when suspension is par to ground
            displacementForceMag *= Math.Abs(JVector.Dot(groundNormal, worldAxis));

            // apply damping
            float dampingForceMag = upSpeed * Damping;

            float totalForceMag = displacementForceMag + dampingForceMag;

            if (totalForceMag < 0.0f)
            {
                totalForceMag = 0.0f;
            }

            JVector extraForce = totalForceMag * worldAxis;

            force += extraForce;

            JVector groundUp   = groundNormal;
            JVector groundLeft = JVector.Cross(groundNormal, wheelFwd);

            if (groundLeft.LengthSquared() > 0.0f)
            {
                groundLeft.Normalize();
            }

            JVector groundFwd = JVector.Cross(groundLeft, groundUp);

            JVector wheelPointVel = car.LinearVelocity +
                                    JVector.Cross(car.AngularVelocity, JVector.Transform(Position, car.Orientation));

            // rimVel=(wxr)*v
            JVector rimVel = angVel * JVector.Cross(wheelLeft, groundPos - worldPos);

            wheelPointVel += rimVel;

            JVector worldVel = worldBody.LinearVelocity +
                               JVector.Cross(worldBody.AngularVelocity, groundPos - worldBody.Position);

            wheelPointVel -= worldVel;

            // sideways forces
            float noslipVel  = 0.1f;
            float slipVel    = 0.1f;
            float slipFactor = 0.7f;

            float smallVel = 3;
            float friction = SideFriction;

            float sideVel = JVector.Dot(wheelPointVel, groundLeft);

            if ((sideVel > slipVel) || (sideVel < -slipVel))
            {
                friction *= slipFactor;
            }
            else
            if ((sideVel > noslipVel) || (sideVel < -noslipVel))
            {
                friction *= 1.0f - (1.0f - slipFactor) * (System.Math.Abs(sideVel) - noslipVel) / (slipVel - noslipVel);
            }

            if (sideVel < 0.0f)
            {
                friction *= -1.0f;
            }

            if (System.Math.Abs(sideVel) < smallVel)
            {
                friction *= System.Math.Abs(sideVel) / smallVel;
            }

            float sideForce = -friction * totalForceMag;

            extraForce = sideForce * groundLeft;
            force     += extraForce;

            // fwd/back forces
            friction = ForwardFriction;
            float fwdVel = JVector.Dot(wheelPointVel, groundFwd);

            if ((fwdVel > slipVel) || (fwdVel < -slipVel))
            {
                friction *= slipFactor;
            }
            else
            if ((fwdVel > noslipVel) || (fwdVel < -noslipVel))
            {
                friction *= 1.0f - (1.0f - slipFactor) * (System.Math.Abs(fwdVel) - noslipVel) / (slipVel - noslipVel);
            }

            if (fwdVel < 0.0f)
            {
                friction *= -1.0f;
            }

            if (System.Math.Abs(fwdVel) < smallVel)
            {
                friction *= System.Math.Abs(fwdVel) / smallVel;
            }

            float fwdForce = -friction * totalForceMag;

            extraForce = fwdForce * groundFwd;
            force     += extraForce;

            // fwd force also spins the wheel
            JVector wheelCentreVel = car.LinearVelocity +
                                     JVector.Cross(car.AngularVelocity, JVector.Transform(Position, car.Orientation));

            angVelForGrip = JVector.Dot(wheelCentreVel, groundFwd) / Radius;
            torque       += -fwdForce * Radius;

            // add force to car
            car.AddForce(force, groundPos + 0.5f * JVector.Up);

            // add force to the world
            if (!worldBody.IsStatic)
            {
                worldBody.AddForce(force * (-1) * 0.01f, groundPos);
            }
        }
예제 #18
0
 public override void UpdateForce(RigidBody body, float duration)
 {
     if (body.Mass < 0.0f) return;
     body.AddForce(VectorGravity * body.Mass);
 }
예제 #19
0
 private void OnJump()
 {
     RigidBody.AddForce(new Vector3(0, 700 * 2, 0));
     didJump = true;
 }
예제 #20
0
 void AddJumpForce()
 {
     RigidBody.AddForce(new Vector3(0, JumpSpeed, 0), ForceMode.Acceleration);
 }
        private void BuildScene()
        {
            // creating two boxShapes with different sizes
            Shape boxShape = new BoxShape(JVector.One);
            Shape groundShape = new BoxShape(new JVector(10, 1, 10));

            // create new instances of the rigid body class and pass 
            // the boxShapes to them
            RigidBody boxBody1 = new RigidBody(boxShape);
            RigidBody boxBody2 = new RigidBody(boxShape);

            boxBody1.Tag = Color.LightPink;
            boxBody2.Tag = Color.LightSkyBlue;

            RigidBody groundBody = new RigidBody(groundShape);

            groundBody.Tag = Color.LightGreen;

            // set the position of the box size=(1,1,1)
            // 2 and 5 units above the ground box size=(10,1,10)
            boxBody1.Position = new JVector(0, 4, 1.0f);
            boxBody2.Position = new JVector(0, 4, -1.0f);

            pointConstraint = new PointConstraint(
                boxBody1, boxBody2, new JVector(0, 4f, 0));

            // add a force to one body - so it's not that boring
            boxBody1.AddForce(JVector.One * 10);

            world.AddConstraint(pointConstraint);

            // make the body static, so it can't be moved
            groundBody.IsStatic = true;

            // add the bodies to the world.
            world.AddBody(boxBody1);
            world.AddBody(boxBody2);
            world.AddBody(groundBody);
        }
예제 #22
0
 public override void LaunchProjectile(Transform @from, Vector3 direction, float power)
 {
     base.LaunchProjectile(@from, direction, power);
     RigidBody.AddForce(direction * power * Time.deltaTime, ForceMode.Impulse);
 }
예제 #23
0
 public override void UpdateForce(RigidBody body, float duration)
 {
     if (body.HasFiniteMass()) return;
     body.AddForce(VectorGravity * body.GetMass());
 }
예제 #24
0
    /**
     * Translates the player
     *@param axis - translation axis, defined by the user inputs
     */
    void Translate(Vector2 axis)
    {
        // apply the translation
        m_TranslationController.UpdateTargetSpeed(axis, GetRunStatus());

        m_Running         = false;
        m_BackwardRunning = false;
        m_WalkingLeft     = false;
        m_WalkingRight    = false;
        bool stillPlaying = false;

        // is the input value large enough to move the player, and the player is lying on the ground or can be controlled while jumping?
        if ((Mathf.Abs(axis.x) > float.Epsilon || Mathf.Abs(axis.y) > float.Epsilon) && (m_AirControl || IsGrounded))
        {
            // always move along the camera forward as it is the direction that it being aimed by the player
            Vector3 desiredMove = Camera.transform.forward * axis.y + Camera.transform.right * axis.x;
            desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;

            // calculate the desired move amplitude
            desiredMove.x *= m_TranslationController.m_CurrentTargetSpeed;
            desiredMove.y *= m_TranslationController.m_CurrentTargetSpeed;
            desiredMove.z *= m_TranslationController.m_CurrentTargetSpeed;

            // run the running animation
            if (IsGrounded)
            {
                // side walking
                if (axis.x > 0.0f)
                {
                    m_WalkingRight = true;

                    if (m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_DoKick &&
                        m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_WalkingRight)
                    {
                        m_ModelController.AnimState = IModelController.IEAnimState.IE_AS_WalkingRight;
                    }
                }
                else
                if (axis.x < 0.0f)
                {
                    m_WalkingLeft = true;

                    if (m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_DoKick &&
                        m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_WalkingLeft)
                    {
                        m_ModelController.AnimState = IModelController.IEAnimState.IE_AS_WalkingLeft;
                    }
                }

                // front or backward running
                if (axis.y > 0.0f)
                {
                    m_Running = true;

                    if (m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_DoKick &&
                        m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_Running)
                    {
                        m_ModelController.AnimState = IModelController.IEAnimState.IE_AS_Running;
                    }
                }
                else
                if (axis.y < 0.0f)
                {
                    m_BackwardRunning = true;

                    if (m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_DoKick &&
                        m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_BackwardRunning)
                    {
                        m_ModelController.AnimState = IModelController.IEAnimState.IE_AS_BackwardRunning;
                    }
                }
            }

            // do move the body?
            if (RigidBody.velocity.sqrMagnitude < (m_TranslationController.m_CurrentTargetSpeed * m_TranslationController.m_CurrentTargetSpeed))
            {
                // move the body by applying a force on it along the player direction
                RigidBody.AddForce(desiredMove * GetSlopeMultiplier(), ForceMode.Impulse);

                // play the footstep on concrete sound
                m_SoundController.Play((int)ISoundController.IEType.IE_T_FootSteps_Concrete);

                // keep the sound playing alive
                stillPlaying = true;
            }
        }

        // set animation to idle if no longer running
        if (m_ModelController.AnimState != IModelController.IEAnimState.IE_AS_DoKick &&
            ((!m_Running && m_ModelController.AnimState == IModelController.IEAnimState.IE_AS_Running) ||
             (!m_BackwardRunning && m_ModelController.AnimState == IModelController.IEAnimState.IE_AS_BackwardRunning) ||
             (!m_WalkingLeft && m_ModelController.AnimState == IModelController.IEAnimState.IE_AS_WalkingLeft) ||
             (!m_WalkingRight && m_ModelController.AnimState == IModelController.IEAnimState.IE_AS_WalkingRight)))
        {
            // check if grounded, in case the jump was not performed by the user (e.g when he falls or hit an obstacle)
            if (IsGrounded)
            {
                m_ModelController.AnimState = IModelController.IEAnimState.IE_AS_Idle;
            }
            else
            {
                m_ModelController.AnimState = IModelController.IEAnimState.IE_AS_Jumping;
            }
        }

        // don't allow single file footsteps to run infinitely
        if (!stillPlaying)
        {
            m_SoundController.Stop((int)ISoundController.IEType.IE_T_FootSteps_Concrete);
        }
    }
예제 #25
0
        public override void Update(GameTime gameTime)
        {
            #region move
            if (Move.X != 0 || Move.Z != 0)
            {
                if (!activeAnimations["Walk"].Playing)
                {
                    activeAnimations["Walk"].Play();
                }

                activeAnimations["Walk"].TimeModifier = new Vector2(RigidBody.LinearVelocity.X, RigidBody.LinearVelocity.Z).Length();

                Vector3 forward = Matrix.CreateRotationY(BodyRotation).Forward;
                Vector2 d       = new Vector2(Move.X, -Move.Z);
                d.Normalize();
                Vector2 a = Vector2.SmoothStep(new Vector2(forward.X, -forward.Z), d, (float)gameTime.ElapsedGameTime.TotalSeconds * 15f);
                BodyRotation = (float)Math.Atan2(a.Y, a.X) - MathHelper.PiOver2;
            }
            else
            {
                activeAnimations["Walk"].Stop();
            }

            Vector3 delta = Move - Velocity;
            delta.Y = 0;
            delta  *= .2f;
            if (delta.LengthSquared() > 0.1f)
            {
                RigidBody.ApplyImpulse(new JVector(delta.X, 0, delta.Z) * RigidBody.Mass);
            }

            JVector   norm;
            float     frac = 0;
            RigidBody hit;
            bool      cast = area.Physics.CollisionSystem.Raycast(RigidBody.Position + (JVector.Down * Height * .5f), JVector.Down,
                                                                  (RigidBody bd, JVector n, float d) => {
                return(bd != RigidBody);
            },
                                                                  out hit, out norm, out frac);

            onGround = cast && frac < .1f;

            if (Move.Y > 0 && Velocity.Y < Move.Y)
            {
                if (onGround)
                {
                    RigidBody.ApplyImpulse(new JVector(0, Move.Y, 0) * RigidBody.Mass);
                }
                else if (Position.Y < area.WaterHeight)
                {
                    Cell cell = area.CellAt(Position);
                    if (cell != null && cell.isLake)
                    {
                        RigidBody.AddForce(new JVector(0, 2 * Move.Y * RigidBody.Mass, 0));
                    }
                }
            }
            #endregion
            #region animate
            List <Pose> curPoses = new List <Pose>();
            foreach (KeyValuePair <string, Animation> kf in activeAnimations)
            {
                kf.Value.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
                if (kf.Value.Playing && !animRemove.Contains(kf.Key))
                {
                    curPoses.Add(kf.Value.getCurrentPose());
                }
            }

            Matrix[] t = new Matrix[transforms.Length];
            for (int i = 0; i < t.Length; i++)
            {
                t[i] = Matrix.Identity;
            }
            int[] weights = new int[transforms.Length];
            foreach (Pose p in curPoses)
            {
                Matrix[] pt = p.getTransforms();
                // go thru all transforms in this pose, add the ones that have more weight
                for (int i = 0; i < t.Length; i++)
                {
                    if (p.Weight >= weights[i] && p.UsesBone(i))
                    {
                        t[i]       = pt[i];
                        weights[i] = p.Weight;
                    }
                }
            }
            transforms = t;

            // rotate head
            transforms[2] = Matrix.CreateTranslation(0, -3f * .125f, 0) *
                            Matrix.CreateRotationX(MathHelper.Clamp(MathHelper.WrapAngle(Look.X), -MathHelper.PiOver2 * .75f, MathHelper.PiOver2 * .75f)) *
                            Matrix.CreateRotationY(MathHelper.Clamp(MathHelper.WrapAngle(Look.Y - BodyRotation), -MathHelper.PiOver2 * .8f, MathHelper.PiOver2 * .8f)) *
                            Matrix.CreateTranslation(0, 3f * .125f, 0);

            foreach (string s in animRemove)
            {
                activeAnimations.Remove(s);
            }
            animRemove.Clear();

            #endregion

            base.Update(gameTime);
        }
예제 #26
0
 /// <summary>
 /// Applies a force at the center of mass.
 /// </summary>
 public override void ApplyForce(Vector3D force)
 {
     jitterBody.AddForce(JitterDatatypesMapping.Convert(ref force));
 }
예제 #27
0
 private void OnJump()
 {
     RigidBody.AddForce(new Vector3(0, 800 * 2, 0));
 }
 public override void Jump()
 {
     RigidBody.AddForce(Vector2.up * JumpForce);
 }
예제 #29
0
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }


            MouseState    mouse = Mouse.GetState();
            KeyboardState keys  = Keyboard.GetState();

            // mouse movement when left-button
            if (mouse.LeftButton == ButtonState.Pressed)
            {
                float x = (lastMouse.X - mouse.X) * 0.2f;
                float y = (lastMouse.Y - mouse.Y) * 0.2f;

                paddle2.Position += new JVector(-x, y, 0f);
                paddle1.Position += new JVector(-x, y, 0f);
            }

            // tilt controls for paddles
            if (keys.IsKeyDown(Keys.Left))
            {
                JMatrix rotated =
                    Conversion.ToJitterMatrix(Matrix.CreateRotationY(MathHelper.ToRadians(1)));

                paddle2.Orientation *= rotated;
                paddle1.Orientation *= rotated;
            }

            if (keys.IsKeyDown(Keys.Right))
            {
                JMatrix rotated =
                    Conversion.ToJitterMatrix(Matrix.CreateRotationY(MathHelper.ToRadians(-1)));

                paddle2.Orientation *= rotated;
                paddle1.Orientation *= rotated;
            }

            if (keys.IsKeyDown(Keys.Up))
            {
                JMatrix rotated =
                    Conversion.ToJitterMatrix(Matrix.CreateRotationX(MathHelper.ToRadians(1)));

                paddle2.Orientation *= rotated;
                paddle1.Orientation *= rotated;
            }

            if (keys.IsKeyDown(Keys.Down))
            {
                JMatrix rotated =
                    Conversion.ToJitterMatrix(Matrix.CreateRotationX(MathHelper.ToRadians(-1)));

                paddle2.Orientation *= rotated;
                paddle1.Orientation *= rotated;
            }


            if (keys.IsKeyDown(Keys.Space))
            {
                ball.AddForce(JVector.Up * 100f);
            }

            // ball and paddle-orientation reset
            if (keys.IsKeyDown(Keys.R))
            {
                ball.IsStatic       = false;
                ball.LinearVelocity = JVector.Zero;
                ball.Position       = new JVector(0f, 9f, 18f);

                float x_variation = (float)(generator.Next(6000) - 3000);

                ball.AddForce(new JVector(x_variation, 1000f, -10000f));

                paddle1.Orientation = JMatrix.Identity;
                paddle2.Orientation = JMatrix.Identity;
            }


            //player.HandleInput(gameTime);

            world.Step(1.0f / 50.0f, true);

            lastMouse = mouse;

            base.Update(gameTime);
        }
예제 #30
0
        public void Update(GameTime gameTime)
        {
            MouseState mouseState = Mouse.GetState();
            //ManipulateScrolling(mouseState);
            Vector2 mousePosition = new Vector2(mouseState.X, mouseState.Y);

            if (mousePosition.X <= 0 || mousePosition.X >= 900 || mousePosition.Y >= 550 || mousePosition.Y <= 0)
            {
                posPressed = new Vector2(0, 0);
                return;
            }
            //if (!IsMouseClickedBefore)
            //{
            if (mouseState.LeftButton == ButtonState.Pressed)
            {
                if (posPressed == new Vector2(0, 0))
                {
                    posPressed = mousePosition;
                }
                if (_isCaptured)
                {
                    //if (StaticData.CurrentVisual2D is RocketCarrierService)
                    //{
                    //    StaticData.EngineManager.RocketsCarrierManagerEngine.RemoveService(StaticData.CurrentVisual2D as RocketCarrierService);
                    //}

                    if (StaticData.CurrentVisual2D is RigidBody)
                    {
                        //_currentSpringService =
                        //    SpringService.CatchSpringServiceForRigidBody(StaticData.CurrentVisual2D as RigidBody);
                        RigidBody rigidBody = StaticData.CurrentVisual2D as RigidBody;
                        switch (StaticData.ManipulationGameMode)
                        {
                        case ManipulationGameMode.TorqueManipulationMode:
                        {
                            Vector3 forceOfTorque = new Vector3(mousePosition.X, mousePosition.Y, 0) -
                                                    new Vector3(mousePositionStart.X,
                                                                mousePositionStart.Y,
                                                                0);
                            forceOfTorque *= rigidBody.Mass;
                            rigidBody.AddTorque(forceOfTorque, mousePositionStart);
                        }
                        break;

                        case ManipulationGameMode.ForceManipulationMode:
                        {
                            Vector3 force = new Vector3(mousePosition.X, mousePosition.Y, 0) -
                                            new Vector3(mousePositionStart.X,
                                                        mousePositionStart.Y,
                                                        0);
                            force *= rigidBody.Mass * 10;
                            rigidBody.AddForce(force);
                        }
                        break;

                        case ManipulationGameMode.DeleteRigidMode:
                            StaticData.EngineManager.RigidsManagerEngine.DeleteRigid(rigidBody);
                            break;

                        case ManipulationGameMode.DragRigidMode:
                            ((RigidBody)
                             StaticData.CurrentVisual2D).PositionXNA = new Vector3(mousePosition.X,
                                                                                   mousePosition.Y,
                                                                                   0);
                            break;
                            //case ManipulationGameMode.DeleteRopesMode:
                            //    TryDeleteRope();
                            //    break;
                            //case ManipulationGameMode.DeleteBubblesMode:
                            //    TryDeleteBubbles();
                            //    break;
                        }
                    }
                    else
                    {
                        switch (StaticData.ManipulationGameMode)
                        {
                        case ManipulationGameMode.DragRigidMode:
                            StaticData.CurrentVisual2D.SetPositionXNA(new Vector3(mousePosition.X,
                                                                                  mousePosition.Y,
                                                                                  0));
                            break;

                        case ManipulationGameMode.DeleteRigidMode:
                            DeleteNonRigidBodies();
                            break;
                        }
                    }
                    if (StaticData.ManipulationGameMode == ManipulationGameMode.SetStaticComps && staticCompsClick == false)
                    {
                        staticCompsClick = true;
                        StaticData.EngineManager.PrefCompsManager.ToggleComponentSetterState(
                            StaticData.CurrentVisual2D);
                    }
                }
                else
                {
                    var tryVisual = CatchVisual2D();
                    if (tryVisual != null)
                    {
                        StaticData.CurrentVisual2D = tryVisual;
                        mousePositionStart         = new Vector3(mousePosition.X, mousePosition.Y, 0);
                        _isCaptured = true;
                    }
                }
            }
            //}
            //if (StaticData.ManipulationGameMode == ManipulationGameMode.DeleteBubblesMode)
            //    TryDeleteBubbles();
            if (mouseState.LeftButton == ButtonState.Released)
            {
                if (posPressed != new Vector2(0, 0) && StaticData.GameSessionMode == SessionMode.PlayingMode)
                {
                    posReleased = mousePosition;
                    TryRopeCut(posPressed, posReleased);
                    posPressed = new Vector2(0, 0);
                }
                _isCaptured      = false;
                staticCompsClick = false;
            }
        }
예제 #31
0
    // Update is called once per frame
    void Update()
    {
        float movement = Input.GetAxis("Horizontal");

        m_rb.AddForce(new Vector3(movement, 0.0F, 0.0F))
    }
예제 #32
0
 void AddMovementForce(Quaternion rotation, Vector3 vector, float speed)
 {
     RigidBody.AddForce(rotation * vector * speed, ForceMode.Acceleration);
 }