Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class Telekinesis : MonoBehaviour
- {
- public float range = 10f; // Range within which objects can be selected
- public float moveSpeed = 10f; // Speed at which objects are moved
- public LayerMask interactableLayer; // Layer that defines which objects can be interacted with
- private Transform selectedObject; // Currently selected object
- void Update()
- {
- if (Input.GetButtonDown("Fire1")) // Change to your desired input for selecting an object
- {
- SelectObject();
- }
- if (selectedObject != null)
- {
- MoveObject();
- }
- if (Input.GetButtonDown("Fire2")) // Change to your desired input for releasing the object
- {
- ReleaseObject();
- }
- }
- void SelectObject()
- {
- RaycastHit hit;
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // Use ray from camera to detect object under mouse
- if (Physics.Raycast(ray, out hit, range, interactableLayer))
- {
- if (hit.collider != null)
- {
- selectedObject = hit.transform;
- }
- }
- }
- void MoveObject()
- {
- // Get mouse position in world space
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- Plane plane = new Plane(Vector3.up, Vector3.zero); // Assuming Y is the up axis
- float distance;
- if (plane.Raycast(ray, out distance))
- {
- Vector3 targetPosition = ray.GetPoint(distance);
- selectedObject.position = Vector3.Lerp(selectedObject.position, targetPosition, Time.deltaTime * moveSpeed);
- }
- }
- void ReleaseObject()
- {
- selectedObject = null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement