- Home /
Rigidbody2D.AddForce works only once?
this code is supposed to allow the user to drag with their mouse to launch the object, and then the object should infinitly bounce off obstacles without losing velocity.
i made a simple scene for testing: (both obstacles only have a BoxColider and a sprite renderer
but when i launch it to the top it bounces of, and then when it hits the bottom one afterwards it just stops. however i want it to just keep bouncing between the top and bottom one.
this is the script:(attached to the main character (the circle))
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Utility : MonoBehaviour
{
public float PushForceMultiplier;
public Vector2 MaxForce;
public Vector2 MinForce;
public Rigidbody2D rb;
private Vector3 StartVector;
private Vector3 EndVector;
private Vector2 Force;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartVector = Camera.main.ScreenToWorldPoint(Input.mousePosition);
StartVector.z = 0;
}
else if (Input.GetMouseButtonUp(0))
{
EndVector = Camera.main.ScreenToWorldPoint(Input.mousePosition);
EndVector.z = 0;
Force = new Vector2(Mathf.Clamp(StartVector.x - EndVector.x, MinForce.x, MaxForce.x), Mathf.Clamp(StartVector.y - EndVector.y, MinForce.y, MaxForce.y));
rb.velocity = new Vector2(0, 0);
rb.AddForce(Force * PushForceMultiplier, ForceMode2D.Impulse);
}
}
void OnCollisionEnter2D(Collision2D CollisionData)
{
rb.velocity = new Vector2(0, 0);
rb.AddForce((-Force * PushForceMultiplier) * new Vector2(-1, 1), ForceMode2D.Impulse);
}
}
all help is very appreciated!
Answer by SpaceManDan · Mar 05, 2021 at 10:05 PM
You are using ForceMode2D.Impulse, https://docs.unity3d.com/ScriptReference/ForceMode.html
You want ForceMode2D.Force (using mass) or ForceMode2D.Acceleration (ignoring Mass)
Impulse = Add an instant force impulse to the rigidbody, using its mass.
That being said, you could just turn the rigidbody drag off and it will just keep flying around until you apply another force to it to stop it... or say, turn the drag back up to stop it when you are ready for it to stop.
Your answer
Follow this Question
Related Questions
Do rigid bodies with force add force to other objects? 0 Answers
Stop movement of rigid bodies 2D after collision 1 Answer
Jumping problems (how to stop a force) 1 Answer
How do I stop a RigidBody2D from moving after applying addForce? 1 Answer
Rigidbody2D adding force vs modifying velocity for character jump 1 Answer