Gravity Gun Script -
Here’s a compact (Unity/C#) that lets you pick up, hold, and launch rigidbody objects with realistic force. It’s designed for a first-person controller and works like the Half-Life 2 gravity gun.
if (Input.GetButton("Fire2")) // Right click hold: Pull object toward you { if (!isHolding) PullObject(); }
void TryGrabObject() { RaycastHit hit; Ray ray = playerCamera.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0)); Gravity gun script
void PullObject() { RaycastHit hit; Ray ray = playerCamera.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
void ThrowObject() { if (heldObject == null) return; Here’s a compact (Unity/C#) that lets you pick
heldObject.useGravity = true; heldObject.drag = 1f; heldObject.velocity = playerCamera.transform.forward * throwForce; heldObject = null; isHolding = false; }
// Rotate object with mouse (optional) float mouseX = Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime; float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed * Time.deltaTime; heldObject.transform.Rotate(Vector3.up, mouseX, Space.World); heldObject.transform.Rotate(Vector3.right, mouseY, Space.World); } } } void TryGrabObject() { RaycastHit hit
private Rigidbody heldObject; private bool isHolding = false;
if (isHolding && heldObject != null) { // Move held object to hold point Vector3 targetPos = holdPoint.position; heldObject.velocity = (targetPos - heldObject.position) * pullForce;







