In the code below, when you click on an object (the fishka tag is assigned to it), the object flies away. Although I must go for a clamped mouse. Moreover, if you refuse from rigidbody and just instead

transform.GetComponent<Rigidbody>().AddForce(rot*0.1f,ForceMode.VelocityChange); 

put the usual

 transform.position = rot; 

That is all ok, the object follows the clamped mouse.

 private Ray ray; private RaycastHit hit; private Vector3 rot = new Vector3(0, 0, 0); void Update() { if (Input.GetMouseButton(0)) { ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit) && hit.collider.CompareTag("fishka")) { rot.z = hit.point.z; rot.x = hit.point.x; transform.GetComponent<Rigidbody>().AddForce(rot*0.1f, ForceMode.VelocityChange); } } } 

accordingly, the question is how to make it so that the rigidbody goes for the clamped mouse.

Here's what it looks like. First we move through transform.position, then through a rigidbody. https://youtu.be/cIrfZoRaWk4

  • If I do not confuse anything, then you have 60 + - once a second (by the number of fps) addforce reaches the object, respectively, a force starts to act on it and it flies away, you constantly addforce to it, it is summed up. - justyx
  • @justyx But it seems like it should be. Only force should be directed to where the mouse is held, even 60 times per second. And it flies right and up. - Dmitrii
  • First, with rigidbody, you need to work in FixedUpdate . Secondly, if you don't need something explosive / impulsive, then try and use a rigidBody.velocity ..... rb.velocity = rot*0.1f; something like this ...... or rather without *0.1f since you are not using it without rigidbidy .... most likely it will not be necessary anyway - Alexey Shimansky
  • one
    @Dmitrii even I missed the moment ..... you need to change the position .... that is, transform.GetComponent<Rigidbody>().position = rot; ...... everything ...... only there should be no rot.z = hit.point.z; and rot.y = hit.point.y; as I understand. ...... and velocity and addforce are a bit different ............ and if you are using 2D, then it should be like a rigidbody2d - Alexey Shimansky
  • one
    You can also try MovePosition , that is, transform.GetComponent<Rigidbody>().MovePosition(rot); ..... here's the difference from transform.GetComponent<Rigidbody>().position = rot; I can not tell. maybe not - Alexey Shimansky

1 answer 1

for dragging objects with a mouse / tach there is a script in a unit called DragRigidbody

I strongly advise you to try :)

And what is written ... and should do exactly what it does, by the way :) Instead of moving after the finger at the coordinates, you give a push to a physical object (ridge body)

  • Where exactly is this script? - Dmitrii
  • one
    Where exactly - I have no idea. Klacni on any object on the scene, in the inspector you click on the "add component" and write its name in the filter. I always added when needed. - Andrew