/// <summary>
 ///     Draws a <seealso cref="Rigidbody2D" />'s trajectory using <seealso cref="Debug" />.DrawLine.
 /// </summary>
 /// <param name="rb"> The body whose trajectory is being drawn. </param>
 /// <param name="force"> For predicting the effects of a Rigidbody2D.AddForce() method. Use Vector2.zero if not needed. </param>
 /// <param name="mode"> Determines how the force vector changes the velocity. Irrelevant when using Vector2.zero. </param>
 /// <param name="color"> The color of the line being drawn. </param>
 /// <param name="trajectoryDuration"> Amount of time in seconds to predict. </param>
 /// <param name="lineDuration"> Amount of time in seconds the drawn line will persist. </param>
 /// <param name="constantForce"> Will the force be applied every FixedUpdate. </param>
 /// <param name='depthTest'> Whether or not the line should be faded when behind other objects. </param>
 public static void DebugTrajectory(this Rigidbody2D rb, Vector2 force, ForceMode2D mode, Color color,
     float trajectoryDuration = 1.0f, float lineDuration = 0.0f, bool constantForce = false, bool depthTest = false)
 {
     var positions = rb.GetTrajectory(force, mode, trajectoryDuration, constantForce);
     for (var i = 0; i < positions.Length - 1; i++)
         Debug.DrawLine(positions[i], positions[i + 1], color, lineDuration, depthTest);
 }
Example #2
0
    public void Mover(float horizontal, float vertical, ForceMode2D mode)
    {
        //Debug.Log("log " + PlayerPrefs.GetInt(PushOrPopPlayerPrefs));
        if (PlayerPrefs.GetInt(PushOrPopPlayerPrefs) == 0)
        {
            direcao = new Vector2(-horizontal, -vertical);
            GetComponent<Tiro>().Atirar(horizontal, vertical, ForceMode2D.Force);
        }
        else
        {
            direcao = new Vector2(horizontal, vertical);
            GetComponent<Tiro>().Atirar(-horizontal, -vertical, ForceMode2D.Force);
        }

        direcao.Normalize();
        direcao.Scale(new Vector2(ForcaImpulso, ForcaImpulso));
        // impulsionando o objeto pra direcao oposta
        for(int i = 0; i < RefPoints.transform.childCount; i++)
        {
            //GameController.GetComponent<Crescer>().MassAddUp(gosma,movimentPorcentReduction);
            RefPoints.transform.GetChild(i).GetComponent<Rigidbody2D>().AddForce(direcao, mode);

        }
        //
        /*for(int i = 1; i < RefPoints.transform.childCount; i++)
        {
            Physics2D.IgnoreCollision(RefPoints.transform.GetChild(i).GetComponent<CircleCollider2D>(), LostMass.GetComponent<CircleCollider2D>());
        }*/
        //RefPoints.GetComponentInChildren<Rigidbody2D>().AddForce(direcao, ForceMode2D.Impulse);
        //gosma.GetComponent<UnityJellySprite>().AddForce(direcao);
    }
Example #3
0
 public void Mover(float horizontal, float vertical, ForceMode2D mode)
 {
     direcao = new Vector2(horizontal * (-1), vertical * (-1));
     direcao.Normalize();
     direcao.Scale(new Vector2(200, 200));
     // impulsionando o objeto pra direcao oposta
     gosma.GetComponent<Rigidbody2D>().AddForce(direcao, mode);
 }
Example #4
0
 public void Push(Vector2 force, ForceMode2D mode)
 {
     Rigidbody2D body = GetComponent<Rigidbody2D> ();
     if (body != null) {
         body.isKinematic = false;
         body.AddForce (force);
         Log (Debugger.Level.Info, "pushed by force ({0})", force);
     }
 }
Example #5
0
	public static void AddRandomForceOnY(this Rigidbody2D body, float Min, float Max, bool randDirection, ForceMode2D mode)
	{
		int direction = 1;
		if(randDirection)
		{
			direction = (Random.value > 0.5f) ? 1 : -1;
		}
		float y = Random.Range (Min, Max); 
		body.AddForce (new Vector2 (0, direction * y), mode);
	}
        public override void Reset()
        {
            gameObject = null;

            torque = null;
            #if UNITY_4_3 || UNITY_4_4
            #else
            forceMode = ForceMode2D.Force;
            #endif
            everyFrame = false;
        }
    /// <summary>
    ///     Draws a <seealso cref="Rigidbody2D" />'s trajectory using <seealso cref="Gizmos" />.DrawLine.
    /// </summary>
    /// <param name="rb"> The body whose trajectory is being drawn. </param>
    /// <param name="force"> For predicting the effects of a Rigidbody2D.AddForce() method. Use Vector2.zero if not needed. </param>
    /// <param name="mode"> Determines how the force vector changes the velocity. Irrelevant when using Vector2.zero. </param>
    /// <param name="color"> The color of the line being drawn. </param>
    /// <param name="trajectoryDuration"> Amount of time in seconds to predict. </param>
    /// <param name="constantForce"> Will the force be applied every FixedUpdate. </param>
    public static void DrawTrajectory(this Rigidbody2D rb, Vector2 force, ForceMode2D mode, Color color,
        float trajectoryDuration = 1.0f, bool constantForce = false)
    {
        var oldColor = Gizmos.color;
        Gizmos.color = color;

        var positions = rb.GetTrajectory(force, mode, trajectoryDuration, constantForce);
        for (var i = 0; i < positions.Length - 1; i++)
            Gizmos.DrawLine(positions[i], positions[i + 1]);

        Gizmos.color = oldColor;
    }
Example #8
0
		public override void Reset()
		{
			gameObject = null;
			atPosition = new FsmVector2 { UseVariable = true };
			vector = null;
			vector3 = new FsmVector3 {UseVariable = true};

			// default axis to variable dropdown with None selected.
			x = new FsmFloat { UseVariable = true };
			y = new FsmFloat { UseVariable = true };
			mode=ForceMode2D.Force;
			everyFrame = false;
		}
Example #9
0
    public void Atirar(float horizontal, float vertical, ForceMode2D mode)
    {
        //Debug.Log("atirou!1");
        //<!-- mesmo vetor de direcao do toque
        direction = new Vector2(horizontal, vertical);
        //-->

        //<!-- adiciona forca na direcao oposta do toque para movimentar a gosma
        //gosma.GetComponent<Rigidbody2D>().AddForce(direction, mode);
        //-->

        //<!-- lanca o projetil do centro para a direcao do toque
        GetComponent<MassaPerdidaSpawn>().GerarMassaPerdida(direction, gosma.transform.position);
        //-->
    }
		public override void Reset()
		{
			gameObject = null;
			atPosition = new FsmVector2 { UseVariable = true };
			vector = null;
			vector3 = new FsmVector3 {UseVariable = true};

			#if UNITY_4_3 || UNITY_4_4
			#else
			forceMode = ForceMode2D.Force;
			space = Space.Self;
			#endif

			// default axis to variable dropdown with None selected.
			x = new FsmFloat { UseVariable = true };
			y = new FsmFloat { UseVariable = true };

			everyFrame = false;
		}
Example #11
0
        public void AddForceAtPosition(Vector2 force, Vector2 position)
        {
            ForceMode2D mode = ForceMode2D.Force;

            INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, mode);
        }
Example #12
0
 private static extern void INTERNAL_CALL_AddRelativeForce(Rigidbody2D self, ref Vector2 relativeForce, ForceMode2D mode);
Example #13
0
 public void AddRelativeForce(Vector2 relativeForce, [DefaultValue("ForceMode2D.Force")] ForceMode2D mode)
 {
     INTERNAL_CALL_AddRelativeForce(this, ref relativeForce, mode);
 }
Example #14
0
 public void AddForce(Vector2 force, [DefaultValue("ForceMode2D.Force")] ForceMode2D mode)
 {
     INTERNAL_CALL_AddForce(this, ref force, mode);
 }
Example #15
0
    public void AddExplosionForce2(Rigidbody2D rb, float explosionForce, Vector2 explosionPosition, float explosionRadius, float upwardsModifier = 0.0F, ForceMode2D mode = ForceMode2D.Force)
    {
        var explosionDir      = rb.position - explosionPosition;
        var explosionDistance = explosionDir.magnitude;

        // Normalize without computing magnitude again
        if (upwardsModifier == 0)
        {
            explosionDir /= explosionDistance;
        }
        else
        {
            // From Rigidbody.AddExplosionForce doc:
            // If you pass a non-zero value for the upwardsModifier parameter, the direction
            // will be modified by subtracting that value from the Y component of the centre point.
            explosionDir.y += upwardsModifier;
            explosionDir.Normalize();
        }

        rb.AddForce(Mathf.Lerp(0, explosionForce, (1 - explosionDistance)) * explosionDir, mode);
    }
Example #16
0
 public void TimeAddForce(Rigidbody2D rb, Vector2 force, ForceMode2D mode)
 {
     rb.AddForce(force * Mathf.Sqrt(m_timeScale), mode);
 }
Example #17
0
 /// <summary>
 /// The equivalent of Rigidbody2D.AddRelativeForce adjusted for time effects.
 /// </summary>
 public void AddRelativeForce(Vector2 force, ForceMode2D mode = ForceMode2D.Force)
 {
     AssertForwardForce();
     rigidbody.AddRelativeForce(AdjustForce(force), mode);
 }
Example #18
0
		private static extern void INTERNAL_CALL_AddRelativeForce(Rigidbody2D self, ref Vector2 relativeForce, ForceMode2D mode);
Example #19
0
		private static extern void INTERNAL_CALL_AddForceAtPosition(Rigidbody2D self, ref Vector2 force, ref Vector2 position, ForceMode2D mode);
    /// <summary>
    ///     Takes a velocity vector, calculates and adds the velocity change amount
    ///     that would be caused by a force with given forcemode against given Rigidbody2D.
    ///     Then Returns the result.
    /// </summary>
    /// <param name="velocity"> The velocity vector to modify. </param>
    /// <param name="rb"> The Rigidbody2D used to calculate how the force is applied. </param>
    /// <param name="force"> The force vector to apply. </param>
    /// <param name="mode"> Determines how the force translates into a change in velocity. </param>
    /// <returns> Velocity vector with force applied. </returns>
    private static Vector2 ApplyForce(this Vector2 velocity, Rigidbody2D rb, Vector2 force, ForceMode2D mode)
    {
        var newVelocity = velocity;

        switch (mode)
        {
            case ForceMode2D.Force:
                newVelocity += (force * Time.fixedDeltaTime) / rb.mass;
                break;
            case ForceMode2D.Impulse:
                newVelocity += (force) / rb.mass;
                break;
        }

        return newVelocity;
    }
 /// <summary>
 ///     Calculates a <seealso cref="Rigidbody2D" />'s trajectory and returns it as an array of position vectors.
 /// </summary>
 /// <param name="rb"> The body whose trajectory is being drawn. </param>
 /// <param name="force"> For predicting the effects of a Rigidbody2D.AddForce() method. Use Vector2.zero if not needed. </param>
 /// <param name="mode"> Determines how the force vector changes the velocity. Irrelevant when using Vector2.zero. </param>
 /// <param name="trajectoryDuration"> Amount of time in seconds to predict. </param>
 /// <param name="constantForce"> Will the force be applied every FixedUpdate. </param>
 /// <returns>
 ///     An array of the body's expected positions after each FixedUpdate in the trajectory. The last index being the
 ///     final position.
 /// </returns>
 public static Vector2[] GetTrajectory(this Rigidbody2D rb, Vector2 force, ForceMode2D mode,
     float trajectoryDuration = 1.0f, bool constantForce = false)
 {
     Vector2[] velocities;
     return rb.GetTrajectory(force, mode, out velocities, trajectoryDuration, constantForce);
 }
    /// <summary>
    ///     Calculates a <seealso cref="Rigidbody2D" />'s trajectory and returns it as an array of position vectors.
    /// </summary>
    /// <param name="rb"> The body whose trajectory is being drawn. </param>
    /// <param name="force"> For predicting the effects of a Rigidbody2D.AddForce() method. Use Vector2.zero if not needed. </param>
    /// <param name="mode"> Determines how the force vector changes the velocity. Irrelevant when using Vector2.zero. </param>
    /// <param name="velocities"> An array of the body's expected velocities at each point along the trajectory. </param>
    /// <param name="trajectoryDuration"> Amount of time in seconds to predict. </param>
    /// <param name="constantForce"> Will the force be applied every FixedUpdate. </param>
    /// <returns>
    ///     An array of the body's expected positions after each FixedUpdate in the trajectory. The last index being the
    ///     final position.
    /// </returns>
    public static Vector2[] GetTrajectory(this Rigidbody2D rb, Vector2 force, ForceMode2D mode, out Vector2[] velocities,
        float trajectoryDuration = 1.0f, bool constantForce = false)
    {
        var maxSpeedErrorThrown = false;
        var physicsFramerate = 1 / Time.fixedDeltaTime;

        if (rb.drag >= physicsFramerate)
            Debug.LogWarning(rb + " Linear Drag(" + rb.drag + ") too high, trajectory Prediction will be inaccurate."
                             + " Maximum safe drag = (1 / Time.fixedDeltaTime), currently: " + (physicsFramerate) +
                             ").");

        trajectoryDuration = Mathf.Max(Time.fixedDeltaTime * 2, trajectoryDuration);
        var points = Mathf.Max(2, Mathf.RoundToInt(trajectoryDuration / Time.fixedDeltaTime));

        var positions = new Vector2[points];
        velocities = new Vector2[points];

        positions[0] = rb.transform.position;
        velocities[0] = rb.velocity;

        // As far as i can tell... (please correct me if i'm wrong)
        // Rigidbody2D.AddForce() applies forces after gravity and drag have already been applied.
        // Rigidbody.AddForce() applies forces before gravity and drag.
        // This only has a noticable difference when comparing large forces against objects with high drag as
        // Rigidbody2D.AddForce is not immediately effected by drag, Rigidbody.AddForce is.

        //Rigidbody2D order:
        //Gravity
        //Drag
        //AddForce()
        //Constraints

        for (var i = 0; i < positions.Length - 1; i++)
        {
            var updatedVelocity = velocities[i];

            updatedVelocity = updatedVelocity.ApplyGravity(rb);
            updatedVelocity = updatedVelocity.ApplyDrag(rb);

            if (i == 0 || constantForce)
                updatedVelocity = updatedVelocity.ApplyForce(rb, force, mode);

            if (!maxSpeedErrorThrown && updatedVelocity.magnitude > Physics2D.maxTranslationSpeed * physicsFramerate)
            {
                Debug.Log(rb + "is expected to reach a speed (" + updatedVelocity.magnitude * Time.fixedDeltaTime +
                          ") greater than Physics2D.maxTranslationSpeed(" + Physics2D.maxTranslationSpeed +
                          ") trajectory prediction may be innaccurate, Consider increasing maxTranslationSpeed," +
                          " mass, linear drag or decreasing manually applied forces");
                maxSpeedErrorThrown = true;
            }

            updatedVelocity = updatedVelocity.ApplyConstraints(rb);

            velocities[i] = updatedVelocity;

            positions[i + 1] = positions[i] + (velocities[i] * Time.fixedDeltaTime);
            velocities[i + 1] = velocities[i];
        }

        return positions;
    }
Example #23
0
 public void AddForce(Vector2 Direction, float Magnitude, ForceMode2D ForceMode)
 {
     rb.AddForce(Direction * Magnitude, ForceMode);
 }
 public override void Jump(float force, ForceMode2D forceMode)
 {
     character.rb2d.AddForce(Vector2.up * force, forceMode);
 }
Example #25
0
 public extern void AddTorque(float torque, [DefaultValue("ForceMode2D.Force")] ForceMode2D mode);
 public void applyForce(Vector2 force, ForceMode2D mode = ForceMode2D.Impulse)
 {
     _rigidbody.AddForce(force, mode);
 }
 /// <summary>
 ///     Calculates a <seealso cref="Rigidbody2D" />'s trajectory and returns it as an array of position vectors.
 /// </summary>
 /// <param name="rb"> The body whose trajectory is being drawn. </param>
 /// <param name="force"> For predicting the effects of a Rigidbody2D.AddForce() method. Use Vector2.zero if not needed. </param>
 /// <param name="mode"> Determines how the force vector changes the velocity. Irrelevant when using Vector2.zero. </param>
 /// <param name="trajectoryDuration"> Amount of time in seconds to predict. </param>
 /// <param name="constantForce"> Will the force be applied every FixedUpdate. </param>
 /// <returns>
 ///     An array of the body's expected positions after each FixedUpdate in the trajectory. The last index being the
 ///     final position.
 /// </returns>
 public static Vector2[] GetTrajectory(this Rigidbody2D rb, Vector2 force, ForceMode2D mode,
                                       float trajectoryDuration = 1.0f, bool constantForce = false)
 {
     Vector2[] velocities;
     return(rb.GetTrajectory(force, mode, out velocities, trajectoryDuration, constantForce));
 }
 public void AddTorque(float torque, ForceMode2D mode = ForceMode2D.Force) { }
    /// <summary>
    ///     Calculates a <seealso cref="Rigidbody2D" />'s trajectory and returns it as an array of position vectors.
    /// </summary>
    /// <param name="rb"> The body whose trajectory is being drawn. </param>
    /// <param name="force"> For predicting the effects of a Rigidbody2D.AddForce() method. Use Vector2.zero if not needed. </param>
    /// <param name="mode"> Determines how the force vector changes the velocity. Irrelevant when using Vector2.zero. </param>
    /// <param name="velocities"> An array of the body's expected velocities at each point along the trajectory. </param>
    /// <param name="trajectoryDuration"> Amount of time in seconds to predict. </param>
    /// <param name="constantForce"> Will the force be applied every FixedUpdate. </param>
    /// <returns>
    ///     An array of the body's expected positions after each FixedUpdate in the trajectory. The last index being the
    ///     final position.
    /// </returns>
    public static Vector2[] GetTrajectory(this Rigidbody2D rb, Vector2 force, ForceMode2D mode, out Vector2[] velocities,
                                          float trajectoryDuration = 1.0f, bool constantForce = false)
    {
        var maxSpeedErrorThrown = false;
        var physicsFramerate    = 1 / Time.fixedDeltaTime;

        if (rb.drag >= physicsFramerate)
        {
            Debug.LogWarning(rb + " Linear Drag(" + rb.drag + ") too high, trajectory Prediction will be inaccurate."
                             + " Maximum safe drag = (1 / Time.fixedDeltaTime), currently: " + (physicsFramerate) +
                             ").");
        }

        trajectoryDuration = Mathf.Max(Time.fixedDeltaTime * 2, trajectoryDuration);
        var points = Mathf.Max(2, Mathf.RoundToInt(trajectoryDuration / Time.fixedDeltaTime));

        var positions = new Vector2[points];

        velocities = new Vector2[points];

        positions[0]  = rb.transform.position;
        velocities[0] = rb.velocity;

        // As far as i can tell... (please correct me if i'm wrong)
        // Rigidbody2D.AddForce() applies forces after gravity and drag have already been applied.
        // Rigidbody.AddForce() applies forces before gravity and drag.
        // This only has a noticable difference when comparing large forces against objects with high drag as
        // Rigidbody2D.AddForce is not immediately effected by drag, Rigidbody.AddForce is.

        //Rigidbody2D order:
        //Gravity
        //Drag
        //AddForce()
        //Constraints

        for (var i = 0; i < positions.Length - 1; i++)
        {
            var updatedVelocity = velocities[i];

            updatedVelocity = updatedVelocity.ApplyGravity(rb);
            updatedVelocity = updatedVelocity.ApplyDrag(rb);

            if (i == 0 || constantForce)
            {
                updatedVelocity = updatedVelocity.ApplyForce(rb, force, mode);
            }

            if (!maxSpeedErrorThrown && updatedVelocity.magnitude > Physics2D.maxTranslationSpeed * physicsFramerate)
            {
                Debug.Log(rb + "is expected to reach a speed (" + updatedVelocity.magnitude * Time.fixedDeltaTime +
                          ") greater than Physics2D.maxTranslationSpeed(" + Physics2D.maxTranslationSpeed +
                          ") trajectory prediction may be innaccurate, Consider increasing maxTranslationSpeed," +
                          " mass, linear drag or decreasing manually applied forces");
                maxSpeedErrorThrown = true;
            }

            updatedVelocity = updatedVelocity.ApplyConstraints(rb);

            velocities[i] = updatedVelocity;

            positions[i + 1]  = positions[i] + (velocities[i] * Time.fixedDeltaTime);
            velocities[i + 1] = velocities[i];
        }

        return(positions);
    }
        public void AddForceTowardsTarget(Vector3 target, ForceMode2D mode = ForceMode2D.Force)
        {
            Vector3 direction = target - this.transform.position;

            this.AddForce(direction.normalized, mode);
        }
    /// <summary>
    ///     Takes a velocity vector, calculates and adds the velocity change amount
    ///     that would be caused by a force with given forcemode against given Rigidbody2D.
    ///     Then Returns the result.
    /// </summary>
    /// <param name="velocity"> The velocity vector to modify. </param>
    /// <param name="rb"> The Rigidbody2D used to calculate how the force is applied. </param>
    /// <param name="force"> The force vector to apply. </param>
    /// <param name="mode"> Determines how the force translates into a change in velocity. </param>
    /// <returns> Velocity vector with force applied. </returns>
    private static Vector2 ApplyForce(this Vector2 velocity, Rigidbody2D rb, Vector2 force, ForceMode2D mode)
    {
        var newVelocity = velocity;

        switch (mode)
        {
        case ForceMode2D.Force:
            newVelocity += (force * Time.fixedDeltaTime) / rb.mass;
            break;

        case ForceMode2D.Impulse:
            newVelocity += (force) / rb.mass;
            break;
        }

        return(newVelocity);
    }
Example #32
0
 public void AddForce(Vector2 force, ForceMode2D mode)
 {
     rb.velocity = Vector3.zero;
     rb.AddForce(force, mode);
 }
Example #33
0
    public static void AddExplosionForce(this Rigidbody2D rb, float explosionForce, Vector2 explosionPosition, float upwardsModifier = 0.0F, ForceMode2D mode = ForceMode2D.Force)
    {
        var explosionDir = rb.position - explosionPosition;

        explosionDir = explosionDir.normalized;
        rb.AddForce(explosionForce * explosionDir, mode);
    }
Example #34
0
        public void AddForce(Vector2 force)
        {
            ForceMode2D mode = ForceMode2D.Force;

            INTERNAL_CALL_AddForce(this, ref force, mode);
        }
Example #35
0
	public void AddForce(Vector2 force, ForceMode2D mode = ForceMode2D.Force)
	{
		if (Rigidbody != null)
			Rigidbody.AddForce(force, mode);
	}
Example #36
0
        public void AddRelativeForce(Vector2 relativeForce)
        {
            ForceMode2D mode = ForceMode2D.Force;

            INTERNAL_CALL_AddRelativeForce(this, ref relativeForce, mode);
        }
    private void AddExplosionForce(Rigidbody2D rb, float explosionForce, Vector2 explodingPosition, float radius, float upwardsModifier = 0f, ForceMode2D mode = ForceMode2D.Impulse)
    {
        BlockDamage component = rb.GetComponent <BlockDamage>();

        if (canExplode)
        {
            explosieAudio.clip = explosie;
            Vector2 a         = rb.position - explodingPosition;
            float   magnitude = a.magnitude;
            explosieAudio.Play();
            if (magnitude < radius / 2f)
            {
                component.minusHealth(3);
            }
            else
            {
                if (magnitude > radius / 3f && magnitude < radius / 2f)
                {
                    component.minusHealth(2);
                }
                if (magnitude > radius && magnitude < radius / 3f)
                {
                    component.minusHealth(1);
                }
            }
            if (upwardsModifier == 0f)
            {
                a /= magnitude;
            }
            else
            {
                a.Normalize();
            }
            rb.AddForce(Mathf.Lerp(0f, explosionForce, radius / magnitude) * a, mode);
        }
        Object.Destroy(base.gameObject);
    }
Example #38
0
 public void AddForceAtPosition(Vector2 force, Vector2 position, [DefaultValue("ForceMode2D.Force")] ForceMode2D mode)
 {
     INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, mode);
 }
Example #39
0
	public void AddForce(Vector2 force, ForceMode2D forceMode) {
		foreach (Rigidbody2D rigid in rigidbodies) rigid.AddForce(force, forceMode);
	}
Example #40
0
 private static extern void INTERNAL_CALL_AddForceAtPosition(Rigidbody2D self, ref Vector2 force, ref Vector2 position, ForceMode2D mode);
 public void AddForce(Vector2 force, ForceMode2D mode = ForceMode2D.Force)
 {
 }
Example #42
0
        public void AddTorque(float torque)
        {
            ForceMode2D mode = ForceMode2D.Force;

            AddTorque(torque, mode);
        }
Example #43
0
    public static void ApplyForceToReachVelocity(Rigidbody2D rigidbody, Vector2 velocity, float force = 1, ForceMode2D mode = ForceMode2D.Force)
    {
        if (force == 0 || velocity.magnitude == 0)
        {
            return;
        }

        velocity = velocity + velocity.normalized * 0.2f * rigidbody.drag;

        //force = 1 => need 1 s to reach velocity (if mass is 1) => force can be max 1 / Time.fixedDeltaTime
        force = Mathf.Clamp(force, -rigidbody.mass / Time.fixedDeltaTime, rigidbody.mass / Time.fixedDeltaTime);

        //dot product is a projection from rhs to lhs with a length of result / lhs.magnitude https://www.youtube.com/watch?v=h0NJK4mEIJU
        if (rigidbody.velocity.magnitude == 0)
        {
            rigidbody.AddForce(velocity * force, mode);
        }
        else
        {
            var velocityProjectedToTarget = (velocity.normalized * Vector3.Dot(velocity, rigidbody.velocity) / velocity.magnitude);
            rigidbody.AddForce((velocity - velocityProjectedToTarget) * force, mode);
        }
    }
Example #44
0
    public static void AddExplosionForce(this Rigidbody2D rb, float explosionForce, Vector2 explosionPosition, float explosionRadius, float upwardsModifier, ForceMode2D mode = ForceMode2D.Impulse)
    {
        var explosionDir      = rb.position - explosionPosition;
        var explosionDistance = explosionDir.magnitude;

        if (upwardsModifier == 0)
        {
            explosionDir /= explosionDistance;
        }
        else
        {
            explosionDir.y += upwardsModifier;
            explosionDir.Normalize();
        }

        rb.AddForce(Mathf.Lerp(0, explosionForce, (1 - explosionDistance)) * explosionDir, mode);
    }
Example #45
0
 public void AddForce(Vector2 force, ForceMode2D mode)
 {
     MyRigidbody.AddForce(force, mode);
 }
Example #46
0
 /// <summary>
 /// The equivalent of Rigidbody2D.AddForceAtPosition adjusted for time effects.
 /// </summary>
 public void AddForceAtPosition(Vector2 force, Vector2 position, ForceMode2D mode = ForceMode2D.Force)
 {
     AssertForwardForce();
     rigidbody.AddForceAtPosition(AdjustForce(force), position, mode);
 }
Example #47
0
        public static void ForceAll(Vector2 startPos, Vector2 endPos, float thickness, float force, ForceMode2D forceMode, int layerMask = -1)
        {
            var right       = (Vector2)Vector3.Cross(endPos - startPos, Vector3.forward).normalized *thickness * 0.5f;
            var force2      = force * right;
            var resultCount = default(int);

            // Left side
            resultCount = Physics2D.LinecastNonAlloc(startPos - right, endPos - right, results, layerMask);

            Force(resultCount, -force2, forceMode);

            // Right side
            resultCount = Physics2D.LinecastNonAlloc(startPos + right, endPos + right, results, layerMask);

            Force(resultCount, force2, forceMode);
        }
Example #48
0
 private void ApplyTorque(GameObject obj, ForceMode2D force)
 {
     obj.GetComponent <Rigidbody2D>()
     .AddTorque(Random.Range(-2f, 2f), force);
 }
Example #49
0
    public static void AddExplosionForce(this Rigidbody2D rb, float force, Vector2 position, float upwardsModifier = 0.0f, ForceMode2D mode = ForceMode2D.Impulse)
    {
        Vector2 explosionDirection = rb.position - position;
        float   explosionDistance  = explosionDirection.magnitude;

        if (upwardsModifier == 0)
        {
            explosionDirection /= explosionDistance;
        }
        else
        {
            explosionDirection.y += upwardsModifier;
            explosionDirection.Normalize();
        }

        float forceToAdd = force - (explosionDistance * 2);

        rb.AddForce(explosionDirection * forceToAdd, mode);
    }
Example #50
0
 public void AddForce(Vector3 force, ForceMode2D force_mode, float duration)
 {
     body.AddForce(force, force_mode);
     setKinematicUntil(duration);
 }
Example #51
0
 /// <summary>
 /// Adds force to the rigidbody
 /// </summary>
 /// <param name="force"></param>
 /// <param name="direction"></param>
 /// <param name="forceMode"></param>
 private void Dash(float force, Vector2 direction, ForceMode2D forceMode)
 {
     ThisRigidbody.AddForce(direction * force, forceMode);
 }