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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Move object to point?

Discussion in 'Physics' started by Sushin, Sep 5, 2016.

  1. Sushin

    Sushin

    Joined:
    May 2, 2015
    Posts:
    25
    I'm trying to essentially make the player pick up a physics object in Unity. I don't (really) want to disable the rigidbody/collider and fake the movement because I want the object to hit walls while it's being held, but I'm not sure what the best way is to get the object to move towards the point (in front of the player) without making it look weird.

    I basically want a Skyrim or Half Life 2 object moving effect. Any ideas of how to go about it?
     
  2. Sushin

    Sushin

    Joined:
    May 2, 2015
    Posts:
    25
    I fixed it. It was embarrassingly easy once I sat and thought of a few ways I could do it.
    This runs in update. If the object is held, I turned gravity off for that object and run this:
    Code (csharp):
    1. Vector3 direction = (Pos_Pickup.position - HeldObject.transform.position).normalized;
    2. float magnitude = 8*Vector3.Distance(Pos_Pickup.position, HeldObject.transform.position);
    3. HeldObject.GetComponent<Rigidbody>().velocity = direction * magnitude;
     
  3. Cybearg

    Cybearg

    Joined:
    Jan 18, 2015
    Posts:
    46
    That's a good idea for the solution. Personally, I've done something similar recently, but I used a dummy GameObject on the player and on the carried object. When picked up, those points overlap. That way, I can easily see where everything will align in the editor.

    I'm a little confused on why you're setting the velocity, though. Wouldn't that cause the HeldObject to go rocketing off in the direction it's being held?
     
  4. Sushin

    Sushin

    Joined:
    May 2, 2015
    Posts:
    25
    The pickup position is in front of the camera where I want the object to be held at. The object moves towards that position with a magnitude based on how far away it is from that position. If the distance of the object from the held position is 0, it will forcibly set the velocity of the object to 0 because it's already at the position. I tried this with rigidbodies "add force" and "move position" but those either worked too well (pushing the object through walls) or not well enough (add force is too wobbly).

    Note: Make sure to set physics bodies like this to continuous dynamic collision detection otherwise they WILL fall through floors on occasion.
     
    Last edited: Sep 6, 2016