Unknown model· unknown
from ShareGPT 90K (shared ChatGPT conversations)
write a unity script of gravity gun
- User
write a unity script of gravity gun
- Assistant
Sure! Here is a basic Unity script for a gravity gun that allows the player to pick up and throw objects in the game world using the mouse:
codeusing System.Collections; using System.Collections.Generic; using UnityEngine; public class GravityGun : MonoBehaviour { public float range = 10f; // The range of the gravity gun public float force = 100f; // The force with which objects are thrown private Camera mainCamera; // The main camera in the scene private Rigidbody grabbedObject; // The object currently being grabbed by the gravity gun // Update is called once per frame void Update() { // Check if the left mouse button is pressed if (Input.GetMouseButtonDown(0)) { // Check if the player is looking at an object within range RaycastHit hit; if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, range)) { // Grab the object grabbedObject = hit.rigidbody; grabbedObject.useGravity = false; // Disable gravity while the object is being grabbed grabbedObject.velocity = Vector3.zero; // Reset the object's velocity } } // Check if the left mouse button is released if (Input.GetMouseButtonUp(0) && grabbedObject != null) { // Throw the object grabbedObject.useGravity = true; // Re-enable gravity grabbedObject.AddForce(mainCamera.transform.forward * force, ForceMode.Impulse); // Apply force to the object in the direction the player is looking grabbedObject = null; // Reset the grabbed object } } }