Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Objects clipping through other when moving them.

Discussion in 'Scripting' started by speedlight1221, Feb 8, 2023.

  1. speedlight1221

    speedlight1221

    Joined:
    Jul 4, 2022
    Posts:
    3
    Hi,

    I made this script that allows me to "lift" objects and move them using the mouse:

    Code (CSharp):
    1. Rigidbody selected;
    2.     float next;
    3.     // Start is called before the first frame update
    4.     void Start()
    5.     {
    6.        
    7.          next = Time.time;
    8.  
    9.     }
    10.  
    11.     // Update is called once per frame
    12.     void Update()
    13.     {
    14.         if (Input.GetMouseButton(0))
    15.         {
    16.             RaycastHit hit;
    17.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    18.  
    19.  
    20.             if(Physics.Raycast(ray, out hit,200.0f))
    21.             {
    22.                 if(hit.transform.tag == "Item")
    23.                 {
    24.                  
    25.                     selected = hit.rigidbody;
    26.  
    27.                 }
    28.             }
    29.  
    30.  
    31.             selected.MovePosition(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f))) ;
    32.         }
    33.  
    34.         if(Input.GetMouseButtonUp(0))
    35.         {
    36.             selected = null;
    37.         }
    However when i do this, it allows me to move the objects trought another object, clipping into the ground. How can i avoid this?
    upload_2023-2-8_20-13-43.png
     
  2. Fatferret

    Fatferret

    Joined:
    Apr 20, 2013
    Posts:
    18
    Hi,

    You need to move it from its current position to the target position in FixedUpdate using AddForce with ForceMode.VelocityChange

    You probably will need to cap the velocity if the mouse is being moved very fast or just set the velocity to 0 if it should just stop
     
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,612
    To add to the above, you can also move rigidbody objects with
    Rigidbody.MovePosition
    and they should respect physics/collisions.

    Also keep in mind a system like this is going to be a lot more than a few lines of code. You will have to code around numerous edge cases. Don't expect a one and done solution here.
     
    BenevolenceGames likes this.
  4. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Unless something has changed, MovePosition just interpolates the RB using its interpolation settings, it does not constrain collissions.
     
    PraetorBlue likes this.