Created
April 10, 2018 18:02
-
-
Save Noxalus/ac914e2a86395a20b0a8b0aafcba495b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class DragObject2D : MonoBehaviour | |
{ | |
public float dampingRatio = 0.5f; | |
public float frequency = 5f; | |
private TargetJoint2D targetJoint; | |
void Update() | |
{ | |
if (!Input.GetMouseButtonDown(0)) | |
return; | |
RaycastHit2D hit = Physics2D.Raycast( | |
Camera.main.ScreenToWorldPoint(Input.mousePosition), | |
Vector2.zero | |
); | |
if (hit.collider == null || !hit.rigidbody || hit.rigidbody.isKinematic) | |
return; | |
if (!targetJoint) | |
{ | |
targetJoint = gameObject.AddComponent<TargetJoint2D>(); | |
targetJoint.dampingRatio = dampingRatio; | |
targetJoint.frequency = frequency; | |
} | |
targetJoint.anchor = transform.InverseTransformPoint(hit.point); | |
StartCoroutine(DragObject()); | |
} | |
IEnumerator DragObject() | |
{ | |
while (Input.GetMouseButton(0)) | |
{ | |
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); | |
targetJoint.target = mousePos; | |
yield return null; | |
} | |
// Release the input | |
Destroy(targetJoint); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment