Untitled
using System.Collections; using System.Collections.Generic; using UnityEditor.Build.Content; using UnityEngine; public class PlayerDragAndDrop : MonoBehaviour { public Camera cam; public Collider draggeableArea; private GameObject draggedObject; private void Start() { draggeableArea = GameObject.Find("Draggeable Area").GetComponent<Collider>(); } void Update() { if (Input.GetMouseButtonDown(0) && draggedObject == null) { SelectDraggeableObject(); } if (Input.GetMouseButton(0) && draggedObject != null) { MoveDraggedObject(); } if (Input.GetMouseButtonUp(0) && draggedObject != null) { DropDraggedObject(); } } void SelectDraggeableObject() { Ray ray = cam.ScreenPointToRay(Input.mousePosition); RaycastHit hit; Debug.DrawRay(ray.origin, ray.direction * 100, Color.red); if (Physics.Raycast(ray, out hit, 100)) { if (hit.collider.TryGetComponent (out DraggeablePlayer draggeablePlayer)) { draggedObject = draggeablePlayer.gameObject; } } } void MoveDraggedObject() { Vector2 cameraToWorldPoint = cam.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y)); Vector3 transformPoint = new Vector3(cameraToWorldPoint.x, cameraToWorldPoint.y, draggedObject.transform.position.z); if (draggeableArea.bounds.Contains(transformPoint)) { draggedObject.transform.position = transformPoint; } } void DropDraggedObject() { draggedObject = null; } }
Leave a Comment