Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to prevent an object move through another object

Discussion in '2D' started by thinh_neyung, Aug 23, 2023.

  1. thinh_neyung

    thinh_neyung

    Joined:
    Mar 29, 2023
    Posts:
    3
    Hi, I have 2 object A and B, I move object B by mouse with OnMouseDrag(), how can I stop moving of object B when it meet object A. I try use collider detect but it only work when I move B slow.
    Thanks alot.
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,468
    Follow the first rule of physics which is that only a Rigidbody2D moves and it'll only detect correct collisions if you use the Rigidbody2D API to cause movement (thousands of tutorials available for that).

    Never set the position/rotation of the Rigidbody2D directly and never ever do the same on the Transform.

    There's a specific joint that can be used for things such as dragging (rigid mouse movement or soft movement etc) known as the TargetJoint2D. You can see it demonstrated in my PhysicsExamples2D project and shown here:



    https://github.com/Unity-Technologi...b/master/Assets/Scripts/Generic/DragTarget.cs
     
    Kurt-Dekker likes this.
  3. thinh_neyung

    thinh_neyung

    Joined:
    Mar 29, 2023
    Posts:
    3
    Thanks for your reply, its very helpful.
     
    MelvMay likes this.