Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using Valve.VR.InteractionSystem;
- public class Pen : MonoBehaviour
- {
- [Header("Pen Properties")]
- public Transform tip;
- public Material drawingMaterial;
- public Material tipMaterial;
- [Range(0.01f, 0.1f)]
- public float penWidth = 0.01f;
- public Color[] penColors;
- [Header("Grabbable")]
- public Interactable interactable;
- private LineRenderer currentDrawing;
- private int index;
- private int currentColorIndex;
- private bool isBeingHeld = false;
- private bool isDrawingOnPaper = false;
- private void Start()
- {
- currentColorIndex = 0;
- tipMaterial.color = penColors[currentColorIndex];
- if (interactable == null)
- {
- interactable = GetComponent<Interactable>();
- }
- interactable.onAttachedToHand += OnGrabbed;
- interactable.onDetachedFromHand += OnReleased;
- }
- private void OnGrabbed(Hand hand)
- {
- isBeingHeld = true;
- }
- private void OnReleased(Hand hand)
- {
- isBeingHeld = false;
- if (currentDrawing != null)
- {
- currentDrawing = null;
- }
- }
- private void Draw()
- {
- if (currentDrawing == null)
- {
- index = 0;
- currentDrawing = new GameObject("Drawing").AddComponent<LineRenderer>();
- currentDrawing.material = drawingMaterial;
- currentDrawing.startColor = currentDrawing.endColor = penColors[currentColorIndex];
- currentDrawing.startWidth = currentDrawing.endWidth = penWidth;
- currentDrawing.positionCount = 1;
- currentDrawing.SetPosition(0, tip.transform.position);
- }
- else
- {
- var currentPosition = currentDrawing.GetPosition(index);
- if (Vector3.Distance(currentPosition, tip.position) > 0.01f)
- {
- index++;
- currentDrawing.positionCount = index + 1;
- currentDrawing.SetPosition(index, tip.position);
- }
- }
- }
- private void Update()
- {
- if (isBeingHeld && isDrawingOnPaper)
- {
- Draw();
- }
- else if (currentDrawing != null)
- {
- currentDrawing = null;
- }
- }
- private void OnTriggerEnter(Collider other)
- {
- if (other.CompareTag("Paper"))
- {
- isDrawingOnPaper = true;
- }
- }
- private void OnTriggerExit(Collider other)
- {
- if (other.CompareTag("Paper"))
- {
- isDrawingOnPaper = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement