Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using DG.Tweening;
- using Sirenix.OdinInspector;
- using UnityEngine;
- public class DragRigidbody : MonoBehaviour
- {
- public float forceAmount = 3000;
- [SerializeField]
- Rigidbody selectedRigidbody;
- [SerializeField]
- Camera targetCamera;
- [SerializeField]
- Vector3 originalScreenTargetPosition;
- [SerializeField]
- Vector3 originalRigidbodyPos;
- [SerializeField]
- float selectionDistance;
- // Start is called before the first frame update
- void Start()
- {
- targetCamera = GetComponent<Camera>();
- }
- void Update()
- {
- if (!targetCamera)
- return;
- if (Input.GetMouseButtonDown(0))
- {
- //Check if we are hovering over Rigidbody, if so, select it
- selectedRigidbody = GetRigidbodyFromMouseClick();
- }
- if (Input.GetMouseButtonUp(0) && selectedRigidbody)
- {
- //Release selected Rigidbody if there any
- selectedRigidbody = null;
- }
- }
- void FixedUpdate()
- {
- if (selectedRigidbody)
- {
- Vector3 mousePositionOffset = targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, selectionDistance)) - originalScreenTargetPosition + Vector3.up * 2;
- // Vector3 mousePositionOffset = targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, 0, Input.mousePosition.y)) - originalScreenTargetPosition + Vector3.up * 2;
- Vector3 velocityVector =
- (originalRigidbodyPos + mousePositionOffset - selectedRigidbody.transform.position) * forceAmount *
- Time.deltaTime;
- selectedRigidbody.velocity = new Vector3(velocityVector.x, 0,velocityVector.z * 6f);
- }
- }
- Rigidbody GetRigidbodyFromMouseClick()
- {
- RaycastHit hitInfo = new RaycastHit();
- Ray ray = targetCamera.ScreenPointToRay(Input.mousePosition);
- bool hit = Physics.Raycast(ray, out hitInfo);
- if (hit)
- {
- if (hitInfo.collider.gameObject.GetComponent<Rigidbody>())
- {
- selectionDistance = Vector3.Distance(ray.origin, hitInfo.point);
- originalScreenTargetPosition = targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, selectionDistance));
- originalRigidbodyPos = hitInfo.collider.transform.position;
- hitInfo.collider.gameObject.transform.DOMove( hitInfo.collider.gameObject.transform.position + Vector3.up
- , 0.2f);
- return hitInfo.collider.gameObject.GetComponent<Rigidbody>();
- }
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement