mirror of
https://github.com/ApfelTeeSaft/Slender.git
synced 2026-08-27 03:43:28 +00:00
110 lines
2.8 KiB
C#
110 lines
2.8 KiB
C#
using System;
|
|
using System.Collections;
|
|
// using System.Collections.Generic;
|
|
// using Boo.Lang;
|
|
using UnityEngine;
|
|
|
|
[Serializable]
|
|
public class DragRigidbody : MonoBehaviour
|
|
{
|
|
public float spring = 50.0f;
|
|
public float damper = 5.0f;
|
|
public float drag = 10.0f;
|
|
public float angularDrag = 5.0f;
|
|
public float distance = 0.2f;
|
|
public bool attachToCenterOfMass = false;
|
|
|
|
private SpringJoint springJoint;
|
|
|
|
void Update()
|
|
{
|
|
if (!Input.GetMouseButtonDown(0))
|
|
return;
|
|
|
|
Camera cam = FindCamera();
|
|
|
|
RaycastHit hit;
|
|
|
|
if (
|
|
Physics.Raycast(
|
|
cam.ScreenPointToRay(Input.mousePosition),
|
|
out hit,
|
|
100f
|
|
)
|
|
&& hit.rigidbody != null
|
|
&& !hit.rigidbody.isKinematic
|
|
)
|
|
{
|
|
if (!springJoint)
|
|
{
|
|
GameObject go = new GameObject("Rigidbody dragger");
|
|
|
|
Rigidbody body = go.AddComponent<Rigidbody>();
|
|
body.isKinematic = true;
|
|
|
|
springJoint = go.AddComponent<SpringJoint>();
|
|
}
|
|
|
|
springJoint.transform.position = hit.point;
|
|
|
|
if (attachToCenterOfMass)
|
|
{
|
|
Vector3 anchor =
|
|
transform.TransformDirection(hit.rigidbody.centerOfMass)
|
|
+ hit.rigidbody.transform.position;
|
|
|
|
anchor = springJoint.transform.InverseTransformPoint(anchor);
|
|
|
|
springJoint.anchor = anchor;
|
|
}
|
|
else
|
|
{
|
|
springJoint.anchor = Vector3.zero;
|
|
}
|
|
|
|
springJoint.spring = spring;
|
|
springJoint.damper = damper;
|
|
springJoint.maxDistance = distance;
|
|
springJoint.connectedBody = hit.rigidbody;
|
|
|
|
StartCoroutine(DragObject(hit.distance));
|
|
}
|
|
}
|
|
|
|
IEnumerator DragObject(float distance)
|
|
{
|
|
float oldDrag = springJoint.connectedBody.linearDamping;
|
|
float oldAngularDrag = springJoint.connectedBody.angularDamping;
|
|
|
|
springJoint.connectedBody.linearDamping = drag;
|
|
springJoint.connectedBody.angularDamping = angularDrag;
|
|
|
|
Camera cam = FindCamera();
|
|
|
|
while (Input.GetMouseButton(0))
|
|
{
|
|
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
|
|
|
|
springJoint.transform.position = ray.GetPoint(distance);
|
|
|
|
yield return null;
|
|
}
|
|
|
|
if (springJoint.connectedBody)
|
|
{
|
|
springJoint.connectedBody.linearDamping = oldDrag;
|
|
springJoint.connectedBody.angularDamping = oldAngularDrag;
|
|
springJoint.connectedBody = null;
|
|
}
|
|
}
|
|
|
|
Camera FindCamera()
|
|
{
|
|
Camera cam = GetComponent<Camera>();
|
|
|
|
if (cam != null)
|
|
return cam;
|
|
|
|
return Camera.main;
|
|
}
|
|
} |