How do I clamp picked up objects with mouse scroll wheel?

Hello!

I’m very new to unity and programming (only been using unity about 1 month)

I’m making a puzzle-escape room game for uni, I have 2 scripts currently, one for picking up, moving and dropping objects, and another for opening and closing doors and drawers (both working!)

I’ve been trying to add a feature to the pickup script so that once an item is picked up , it snaps to the “Hold Area” and I can use the mouse scroll wheel to zoom an item towards or away from the player, I do want it clamped though so the player can’t infinitely scroll the item out of bounds or through the camera!

Below is what I have for the pickup script!

using UnityEngine;
using System;
using UnityEditor;
public class PickupController : MonoBehaviour
{
    [Header("Pickup Settings")]
    [SerializeField] public Transform holdArea;
    private GameObject heldObject;
    private Rigidbody heldObjectRB;

    [Header("Physics Parameters")]
    [SerializeField] private float pickupRange = 5.0f;
    [SerializeField] private float pickupForce = 150.0f;

    [Header("Zoom Settings")]
    [Space]
    private bool pickedUp;
    private bool positionSet;
    public LayerMask layerMask;

    private float currentZoom;
    private float minZoom = -1.0f;
    private float maxZoom = 0.1f;

    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            if(heldObject == null)
            {
                RaycastHit hitnew;

                if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hitnew, pickupRange))
                {
                    PickupObject(hitnew.transform.gameObject);
                    currentZoom = 0;
                }
            }
            else
            {
                DropObject();
            }
        }
        if(heldObject != null)
        {
            MoveObject();
        }
        
        if(pickedUp)
        {
            //Vector3 newPos = new Vector3(heldObject.transform.position.x, heldObject.transform.position.y, Mathf.Clamp(heldObject.transform.position.z, -0.18f, 1f));

            var zoom = Input.GetAxis("Mouse ScrollWheel");

            Debug.Log(currentZoom);
            Debug.Log(maxZoom);

            currentZoom += zoom;
            currentZoom = Mathf.Clamp(currentZoom, minZoom, maxZoom);

            if (currentZoom < maxZoom && currentZoom > minZoom)
            {
                heldObject.transform.Translate(Camera.main.transform.forward * Time.deltaTime * 100 * Input.GetAxis("Mouse ScrollWheel"), Space.World);
            }
            heldObjectRB.constraints= RigidbodyConstraints.FreezeRotation; 
        }
        else
        {
            return;
        }
    }

    void MoveObject()
    {
        if(Vector3.Distance(heldObject.transform.position, holdArea.position) > 0.1f)
        {
            Vector3 moveDirection = (holdArea.position - heldObject.transform.position);
            heldObjectRB.AddForce(moveDirection * pickupForce);
        }
    }

    void PickupObject(GameObject pickObj)
    {
        if(pickObj.GetComponent<Rigidbody>())
        {
            pickedUp = true;
            heldObjectRB = pickObj.GetComponent<Rigidbody>();
            heldObjectRB.useGravity = false;
            heldObjectRB.drag = 10;    // Drag force is 10.
            heldObjectRB.constraints = RigidbodyConstraints.FreezeRotation;
            heldObjectRB.constraints = RigidbodyConstraints.FreezePosition;
            heldObjectRB.isKinematic = true;
            heldObjectRB.transform.parent = holdArea;
            heldObject = pickObj;
            heldObject.transform.SetPositionAndRotation(Camera.main.transform.forward, heldObject.transform.rotation);
            Vector3 position = new Vector3(heldObject.transform.position.x, heldObject.transform.position.y, Mathf.Clamp(Mathf.Abs(Camera.main.transform.position.z - heldObject.transform.position.z), -0.18f, 0.1f));
            heldObject.transform.SetPositionAndRotation(position, heldObject.transform.rotation);
        }
    }

    void DropObject()
    {
        pickedUp = false;
        heldObjectRB.useGravity = true;
        heldObjectRB.drag = 1;
        heldObjectRB.constraints = RigidbodyConstraints.None;
        heldObjectRB.isKinematic = false;
        heldObject.transform.parent = null;
        heldObject = null;
    }
}

I’m using unity version 2022.3.47f1 and visual studio 17.11.3

The player has an arm, with a “Hold Area” at the end, this is where the objects attach to. The z-axis is always pointing outwards of the arm, moving with player movements.

Line 51 was an attempt from one of my teachers, but the line wasn’t being called

Line 53-63 & 95-97 is help I got from a friend who’s familiar with programming, but not with unity. We’ve been getting closer and closer to getting this one right, but currently once the object gets picked up it is behind the player and in the ground.

The pickup controller is working, but I cannot seem to figure out the clamping for held objects!

Please let me know if you require any more info!

Thank you greatly!! :slight_smile:

One thing to really helps these sorts of things is to parent the grabbed object to you, then only change its localPosition, probably only along the z axis.

The script becomes quite simple, really just five important lines doing the work in Update():

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// @kurtdekker - mousewheel to move us in / out of the camera's line of sight
//
// to use:
//
//	- blank scene, Main Camera, Light
//	- make a cube primiative
//	- drop this script on it
//	- press PLAY
//	- roll the scrollwheel
//
public class GrabWheel : MonoBehaviour
{
	float forwardDistance;

	float minDistance = 4;
	float maxDistance = 6;

	float rate = 1.0f;

	// offset from centerline of camera
	float xOffset = +1;
	float yOffset = -2;

	void Start ()
	{
		// parent us to the main camera when things start
		Camera cam = Camera.main;
		transform.SetParent(cam.transform);
	}
	
	void Update ()
	{
		// read input
		float scroll = Input.GetAxis("Mouse ScrollWheel");			

		// scale
		scroll *= rate;

		// adjust
		forwardDistance += scroll;

		// clamp
		forwardDistance = Mathf.Clamp( forwardDistance, minDistance, maxDistance);

		// set local position
		transform.localPosition = new Vector3( xOffset, yOffset, forwardDistance);
	}
}

Hello!

I’m not sure what happened but this put my camera in the ground whilst picking up objects

I’ve got a screen recording of the programming and how it looks when you click play

Thank you!

If you’re not sure, imagine how unsure we are!

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?

All that info was provided in original post, just looking for some help, thanks.