- Home /
Gameobject going past target when using rigidbody2d.addforce
I have a C# script where an enemy in my game is meant to be thrown around by the mouse when I'm holding down left click, i got this to work with rb.addforce with the target being an object that is constantly at the same position as the mouse. It works fine, but whenever I hold down the mouse for too long, the enemy flies past and never loses its momentum, here is my program
 public class EnemyThrowing : MonoBehaviour
 {
 
     public Rigidbody2D rb;//enemy rigidbody
     public Transform mouse; //transform of "cursor" gameobject
     private Vector2 _mousePosition; // position of "cursor" transform
     // Update is called once per frame
     void Update()
     {
         _mousePosition = mouse.position; //set _mousePosition to position of "cursors" transform, keeps mouse position accurate after first frame
         print(Input.mousePosition); 
         if (Input.GetMouseButton(0)) 
         {
             rb.AddForce(_mousePosition, ForceMode2D.Force); //add force in the direction of "cursors" position, is a constant force and is affected by mass
         } else if(Input.GetMouseButtonUp(0))
         {
             rb.AddForce(-rb.velocity, ForceMode2D.Force); //slows down enemy after letting go of mouse
         }
 
     }
 }
thank you from the past!
Answer by camdenlink7 · Jun 19, 2019 at 02:10 PM
You will need to limit the speed of the enemy. I am not sure how to do this off the top of my head, but if you dig around I am sure that you can find it. I think it basically is just saying if the speed of the object (with the rigidbody2d on it) goes above a certain value, then it will set it back to that max value. I hope this helps! Sorry I couldn't remember exactly.
Your answer
 
 
             Follow this Question
Related Questions
Rigidbody2D.AddForce works only once? 1 Answer
Rigidbody2D.velocity is not working. 0 Answers
Rigidbody2D adding force vs modifying velocity for character jump 1 Answer
How do I stop a RigidBody2D from moving after applying addForce? 1 Answer
How can i initiate an object in parabolic motion without using gravity using Rigidbody2D? 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                