Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.UI;
- [RequireComponent(typeof(PolygonCollider2D))]
- public class AxisObject : MonoBehaviour {
- private Plane dragPlane;
- private Vector3 offset;
- private Camera myMainCamera;
- Vector3 initial;
- [Header("Axis")]
- public Axis axis;
- [Header("Response Colors")]
- [SerializeField] SpriteRenderer MyRenderer;
- [SerializeField] Color NormalColor;
- [SerializeField] Color HighlightColor;
- [SerializeField] Color ClickOrDragColor;
- void Start()
- {
- myMainCamera = Camera.main;
- }
- [SerializeField] GameObject Thing;
- public void ThingToDrag(GameObject newLink) {
- Thing = newLink;
- }
- void OnMouseEnter() {
- MyRenderer.color = HighlightColor;
- }
- void OnMouseDown()
- {
- //just getting all the shit ready
- MyRenderer.color = ClickOrDragColor;
- dragPlane = new Plane(myMainCamera.transform.forward, transform.position);
- Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);
- float planeDist;
- dragPlane.Raycast(camRay, out planeDist);
- offset = transform.position - camRay.GetPoint(planeDist);
- }
- void OnMouseDrag() //this happens when I drag something related to the object (obviously)
- {
- MyRenderer.color = ClickOrDragColor;
- Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);
- float planeDist;
- dragPlane.Raycast(camRay, out planeDist);
- // Get the new position with the offset
- Vector3 newPosition = camRay.GetPoint(planeDist) + offset;
- // Calculate the difference in position
- Vector3 deltaPosition = newPosition - initial;
- // Set the object's position based on the axis
- if (axis == Axis.X)
- Thing.transform.position = new Vector3(newPosition.x, Thing.transform.position.y, Thing.transform.position.z);
- else if (axis == Axis.Y)
- Thing.transform.position = new Vector3(Thing.transform.position.x, newPosition.y, Thing.transform.position.z);
- else if (axis == Axis.Z)
- Thing.transform.position = new Vector3(Thing.transform.position.x, Thing.transform.position.y, newPosition.z);
- // Update the initial position for the next frame
- initial = newPosition;
- }
- void OnMouseExit() {
- MyRenderer.color = NormalColor;
- }
- void OnMouseUp() {
- MyRenderer.color = NormalColor;
- }
- }
- public enum Axis {
- X, Y, Z
- }
Advertisement
Add Comment
Please, Sign In to add comment