UP-Viagg-io/Viagg-io/Assets/Scripts/SliceObjectsVR.cs

85 lines
3.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EzySlice;
using UnityEngine.InputSystem;
using UnityEngine.XR.Interaction.Toolkit;
public class SliceObjectsVR : MonoBehaviour
{
public Transform startSlicePoint;
public Transform endSlicePoint;
public LayerMask sliceableLayer;
public Material crossSectionMaterial;
public float cutForce = 0.1f;
public float explosionRadius = 0.1f;
private Vector3 lastSlicerPosition; // Letzte Position von SLICER
private Vector3 slicerVelocity; // Berechnete Geschwindigkeit von SLICER
void Start()
{
lastSlicerPosition = transform.position; // Startposition speichern
}
void FixedUpdate()
{
// Berechnung der Geschwindigkeit von SLICER
slicerVelocity = (transform.position - lastSlicerPosition) / Time.fixedDeltaTime;
lastSlicerPosition = transform.position;
// Debugging: Prüfen, ob die Velocity sinnvoll ist
//Debug.Log($"SLICER Velocity: {slicerVelocity}, Magnitude: {slicerVelocity.magnitude}");
// Prüfen, ob ein schneidbares Objekt getroffen wird
bool hasHit = Physics.Linecast(startSlicePoint.position, endSlicePoint.position, out RaycastHit hit, sliceableLayer);
if (hasHit)
{
GameObject target = hit.transform.gameObject;
Slice(target);
}
}
public void Slice(GameObject target)
{
//Debug.Log("Slice Function active: " + target.name);
// Normalenvektor für die Schnittebene berechnen
Vector3 planeNormal = Vector3.Cross(endSlicePoint.position - startSlicePoint.position, slicerVelocity);
planeNormal.Normalize();
//Debug.Log($"Direction: {planeNormal}, Magnitude: {planeNormal.magnitude}");
//Debug.Log($"Velocity: {slicerVelocity}, Magnitude: {slicerVelocity.magnitude}");
// Prüfen, ob das Objekt geschnitten werden kann
SlicedHull hull = target.Slice(endSlicePoint.position, planeNormal);
if (hull != null)
{
//Debug.Log("Hull isn't empty");
GameObject upperHull = hull.CreateUpperHull(target, crossSectionMaterial);
SetupSlicedComponent(upperHull);
GameObject lowerHull = hull.CreateLowerHull(target, crossSectionMaterial);
SetupSlicedComponent(lowerHull);
Destroy(target);
}
}
public void SetupSlicedComponent(GameObject slicedObject)
{
//Debug.Log("New object created");
Rigidbody rb = slicedObject.AddComponent<Rigidbody>(); //add Rigidbody
MeshCollider collider = slicedObject.AddComponent<MeshCollider>(); //add Meshcolider
collider.convex = true; //make Collider convex
rb.AddExplosionForce(cutForce, slicedObject.transform.position, explosionRadius); //add force for realistic behaviour
slicedObject.layer = 6; // 6 = "sliceableLayer"
slicedObject.AddComponent<XRGrabInteractable>(); //add grabbable Script
slicedObject.AddComponent<ComponentController>(); //add BT-Controller
slicedObject.AddComponent<OnGrabSound>(); //add grab sound
slicedObject.AddComponent<OnCollideSound>(); //add collision sound
}
}