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 How to fix objects clip through walls picked up by Gravity Gun?

Discussion in 'Scripting' started by zielakless, Mar 29, 2023.

  1. zielakless

    zielakless

    Joined:
    Jan 31, 2019
    Posts:
    3
    Hi, I've been trying for a few days to write a script that will allow me to manipulate objects using "Gravity Gun", but I have a problem with objects penetrating through walls.
    I tried using Vector3.Dot, but the offset only applies to one side of the object.

    Code (CSharp):
    1. if(Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, Mathf.Infinity, ignoreTargetMask)) {
    2.             float upDot = Vector3.Dot(hit.normal, Vector3.up);
    3.  
    4.             target.position = new Vector3(hit.point.x, hit.point.y + target.GetComponent<Collider>().bounds.extents.y * upDot, hit.point.z);
    5. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,888
    I would give the box a Rigidbody and use FixedUpdate to adjust its velocity such that it is moving towards the desired position, rather than setting the position directly. The physics engine will handle the rest.

    Some small logic will be needed to handle the problem of overshooting the target (set velocity lower when it will overshoot the target based on the current distance / velocity / fixed timestep), but this is a more minor issue.
     
  3. zielakless

    zielakless

    Joined:
    Jan 31, 2019
    Posts:
    3
    The thing is that object is scaling by distance between camera and held object (just like in Superliminal)
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,888
    I don't think that's a problem. The scaling part only needs to happen at the moment that you are picking the object up. The physics approach I suggested would still be workable.

    If you still want to do manual physics queries instead you should be using BoxCast with a box that matches your actual box and using that hit data to limit the motion of your box.