"Pick up a object, and walk around with it script. Item starts flying up to the air instead" (613510)

So i’m currently working on a script that can pick up an item, and drop it with the click of the left mouse button. I’m also planning on addint rotating of an item and some icons to display whenever i do one of those actions.

I’m currently very new to this, so i might be trowing myself out in the depths. But i would like to try.

Here’s my code:

public class PickUp : MonoBehaviour {

    public Transform onHand;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if(Input.GetMouseButton(1)){
            this.transform.position = onHand.position;
        }
    }

    void OnMouseDown () {



        GetComponent<Rigidbody>().useGravity = false;
        this.transform.position = onHand.position;
        this.transform.parent = GameObject.Find("Player").transform;
    }

    void OnMouseUp () {
        this.transform.parent = null;
        GetComponent<Rigidbody>().useGravity = true;
    }
}

Currently i have a gameObject, that holds the object in front of the player.

So far it kind of works.. I’ve some trouble picking up my object, it does not always let me. I have to click a couple of times, before it actually gets a hold on the object. When it does, the objects starts flying upwards for some weird reason i do not understand. I still have a hold on it, i can still walk around with it and as soon as i let go it falls down. I hope you guys can help me!

Make sure to put the code in code blocks on the forum so that it’s easy to read.

//Like this!

Quote me if you want to see how to write that out.

So then, let me look at this:

public class PickUp : MonoBehaviour {

    public Transform onHand;

    // Use this for initialization
    void Start () {
 
    }
 
    // Update is called once per frame
    void Update () {
        if(Input.GetMouseButton(1)){
            this.transform.position = onHand.position;
        }
    }

    void OnMouseDown () {



        GetComponent<Rigidbody>().useGravity = false;
        this.transform.position = onHand.position;
        this.transform.parent = GameObject.Find("Player").transform;
    }

    void OnMouseUp () {
        this.transform.parent = null;
        GetComponent<Rigidbody>().useGravity = true;
    }
}

EDIT: Okay, to start I wouldn’t turn off gravity. That screws with the physic in unnecessary ways. Instead make a state where the object moves towards the mouse when it is clicked on and then turns off when it’s done.

I’m assuming that if you want to turn it you also want it to collide with things while you’re moving is around. Correct?

I’m really new to Unity, so i’m not quite sure on how to do things. I followed a tutorial i found on youtube, that is outdated now… So I couldn’t get my script to work… Well yes i want it to be able to collide with stuff!

Okay, give me a second. (I’m currently not at a computer with Unity on it so I’m going to have to wing it).

I’ve found that, if i disable gravity on my rigidbody and use Is kinematic, it stops flowing upwards. But it does not fall to the ground anymore.

Is this a first person game, a 2d game, or a 3d game?

I need to know to figure out where the move the object to.

public class PickUp : MonoBehaviour {

public Bool isPickedUp;
private Rigidbody myRigidbody;

// Use this for initialization
 void Start () {
  //this caches the rigidbody so it doesn't have to look it up constantly
  myRigidbody = GetComponent<Rigidbody>();
  isPickedUp = false;
 }

 void OnMouseDown() {
  isPickedUp = true;
 }

 void OnMouseUp() {
  isPickedUp = false;
 }

 //Since this is a physics movement, do it in the fixed update
 void FixedUpdate() {
  if (isPickedUp == true){
   //Script that tells the object to move
  }
 }

}

This is a 3d game, the variable known as onHand is where the item is going to be positioned in the game.

So when you move, does the camera move? Or is there a mouse pointer that moves around the screen?

public class PickUp : MonoBehaviour {

public Float moveSpeed;
public Transform target;
private Bool isPickedUp;
private Transform myTransform;

// Use this for initialization
void Start () {
//this caches the transform so it doesn't have to look it up constantly
myTransform = transform;
isPickedUp = false;
}

void OnMouseDown() {
isPickedUp = true;
}

void OnMouseUp() {
isPickedUp = false;
}

//Since this is a physics movement, do it in the fixed update
void FixedUpdate() {
if (isPickedUp == true){
//Script that tells the object to move
transform.position = Vector3.MoveTowards(myTransform.position, target.position, moveSpeed * Time.fixedDeltaTime);
}
}

}

This should move the object to what you designate as the “target” variable when you click on the object this is attached to.

Tried you’re code, so far you can kind of drag the object around the floor hehe.

There’s a player object, inside of the player object there is a Main Camera and a object called GameObject. Here’s my firstpersoncontroller:

[RequireComponent (typeof(CharacterController))]
public class FirstPersonController : MonoBehaviour {

    //hastighed af diverse bevægelser
    public float movementSpeed = 3.0f;
    public float mouseSensitivity = 5.0f;
    public float jumpSpeed = 20.0f;

    float verticalRotation = 0;
    public float upDownRange = 60.0f;

    float verticalVelocity = 0;

    CharacterController characterController;

    // Use this for initialization
    void Start () {
        //Cursor.visible = false;
        //Cursor.lockState = CursorLockMode.Locked;
        characterController = GetComponent<CharacterController>();
    }
  
    // Update is called once per frame
    void Update () {

        //Rotering af spilleren,
        float rotLeftRight = Input.GetAxis ("Mouse X") * mouseSensitivity;
        transform.Rotate(0, rotLeftRight, 0);

        verticalRotation -= Input.GetAxis ("Mouse Y") * mouseSensitivity;
        verticalRotation = Mathf.Clamp (verticalRotation, -upDownRange, upDownRange);
        Camera.main.transform.localRotation = Quaternion.Euler (verticalRotation, 0, 0);

        // Bevægelse af spilleren            
        float forwardSpeed = Input.GetAxis ("Vertical") * movementSpeed;
        float sideSpeed = Input.GetAxis ("Horizontal") * movementSpeed;

        verticalVelocity += Physics.gravity.y * Time.deltaTime;

        if (characterController.isGrounded && Input.GetButton ("Jump")) {
            verticalVelocity = jumpSpeed;
        }

        Vector3 speed = new Vector3 (sideSpeed, verticalVelocity, forwardSpeed);
        speed = transform.rotation * speed;

        characterController.Move(speed * Time.deltaTime);


    }
}

AH!

Okay, this is a first person controller. That changes things. So you want to move things about like they do in Bethesda games.

First, make an empty point on the character controller and place it where you want the item to move towards, such as a meter in front of the camera and 1/2 meter down.

You’re going to want to cast a ray out of the camera a short distance every frame (don’t worry, it’s cheap).

Then have it check what it collides with.

If the object is able to be picked up turn on a visual cue, such as a GUI prompt.

If the mouse button is pressed down while it has the prompt up have it go to a “carry state” and set the item’s transform to the script’s cached transform.

Move the item’s transform to the empty point. You may also want to increase the movement speed as the item gets further away from the target point.

Also, run a check to see if the distance between the player and the object is too far. If it is, turn off the carry state and drop the item.

And of course, turn off the carry state on mouse up.

This is actually a little bit more code, but I promise it’s not that bad.

Unfortunately I’m out of time right now, but I’ll try to get back to it later.

I really like how amnesia did it! I’m lost in all of those words you are saying. xD I’m quite the newbie atm, and i followed a tutorial for all i’ve done so far…

Okay, this may help:

  1. Nest an new empty game object inside the camera. Move the game object to where you are going to want to have items you pick up move to.

  2. Create a cube and change its tag to “Item” or something like that.

  3. Create a new script on the camera. And add these variables:
    -A Transform to cache the camera’s position.
    -A Transform for the Empty Game Object.
    -A Transform for the item.
    -A Bool for the script’s state.
    -A Float for the item’s movement speed.
    -A Float for how far you want to reach.
    -A Float for how far you want to be from the object before you drop it.

  4. Shoot a ray straight out of your camera in the Update function and make it the length that you want your reach to be. About five units sounds about right.

  5. Have the ray test the tag of it’s what it hits. If it’s “item” have a prompt to show that you can pick it up, such as turning on an item on the GUI canvas.

  6. On Mouse Down shoot out a ray and set the Target variable to the item’s transform and set a bool on so the script now knows that it is carrying an object.

  7. In the fixed update tell the item’s transform to move towards the Empty Game Object if the carrying bool is true.

  8. In the update check the distance between the camera and the item. If it goes above a threshold, set the carrying bool to false.

  9. On mouse up turn off the carrying bool.