Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class MouseContorls : MonoBehaviour
- {
- Camera cam;
- bool go = false;
- MeshFilter filter;
- Mesh mesh;
- [HideInInspector]
- public Vector3[] verticles;
- int target;
- public float pullValue = .3f;
- public float radius = 0.3f;
- Vector3 from;
- Vector3 to;
- Vector3 current;
- #pragma warning disable CS0108
- MeshCollider collider;
- public GameObject gameObject;
- #pragma warning restore CS0108
- private void Start()
- {
- cam = Camera.main;
- filter = gameObject.GetComponent<MeshFilter>();
- collider = gameObject.GetComponent<MeshCollider>();
- mesh = filter.mesh;
- verticles = mesh.vertices;
- }
- void Update()
- {
- if (Input.GetMouseButtonDown(0))
- {
- RaycastHit hit;
- from = Input.mousePosition;
- from.z = 0;
- if (Physics.Raycast(cam.ScreenPointToRay(from), out hit))
- {
- target = GetClosestVertex(hit.point - gameObject.transform.position);
- current = verticles[target];
- go = true;
- }
- }
- if (go)
- {
- //Debug.DrawLine(gameObject.transform.position+verticles[target], gameObject.transform.position+verticles[target] * 2);
- if (Input.GetMouseButtonUp(0))
- {
- go = false;
- collider.sharedMesh = mesh;
- }
- Debug.Log(to - from);
- if(to != Input.mousePosition)
- DisplaceVertices(verticles[target], to-from);
- to = Input.mousePosition;
- to.z = 0;
- }
- }
- void DisplaceVertices(Vector3 targetVertexPos, Vector3 fromto)
- {
- Vector3 currentVertexPos = Vector3.zero;
- float sqrRadius = radius * radius;
- for (int i = 0; i < verticles.Length; i++)
- {
- currentVertexPos = verticles[i];
- float sqrMagnitute = Distance(currentVertexPos,targetVertexPos);
- if (sqrMagnitute > sqrRadius)
- {
- continue;
- }
- float distance = Mathf.Sqrt(sqrMagnitute);
- float falloff = (radius-distance) /radius;
- Vector3 translate = currentVertexPos + fromto * falloff * Time.deltaTime * 0.1f;
- verticles[i] = translate;
- }
- mesh.vertices = verticles;
- mesh.RecalculateNormals();
- }
- int GetClosestVertex(Vector3 point)
- {
- int closest = -1;
- float currentDistance = 0;
- float cacheDistance = float.MaxValue;
- int i;
- for (i = 0; i < verticles.Length; i++)
- {
- currentDistance = Distance(verticles[i], point);
- if (currentDistance < cacheDistance)
- {
- closest = i;
- cacheDistance = currentDistance;
- }
- }
- return closest;
- }
- public float Distance(Vector3 one,Vector3 two) {
- float xD = one.x - two.x;
- float yD = one.y - two.y;
- float zD = one.z - two.z;
- return xD * xD + yD * yD + zD * zD;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement