2
0

TargetHitEffect.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. using UnityEngine;
  3. using System.Collections;
  4. namespace Valve.VR.InteractionSystem.Sample
  5. {
  6. public class TargetHitEffect : MonoBehaviour
  7. {
  8. public Collider targetCollider;
  9. public GameObject spawnObjectOnCollision;
  10. public bool colorSpawnedObject = true;
  11. public bool destroyOnTargetCollision = true;
  12. private void OnCollisionEnter(Collision collision)
  13. {
  14. if (collision.collider == targetCollider)
  15. {
  16. ContactPoint contact = collision.contacts[0];
  17. RaycastHit hit;
  18. float backTrackLength = 1f;
  19. Ray ray = new Ray(contact.point - (-contact.normal * backTrackLength), -contact.normal);
  20. if (collision.collider.Raycast(ray, out hit, 2))
  21. {
  22. if (colorSpawnedObject)
  23. {
  24. Renderer renderer = collision.gameObject.GetComponent<Renderer>();
  25. Texture2D tex = (Texture2D)renderer.material.mainTexture;
  26. Color color = tex.GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
  27. if (color.r > 0.7f && color.g > 0.7f && color.b < 0.7f)
  28. color = Color.yellow;
  29. else if (Mathf.Max(color.r, color.g, color.b) == color.r)
  30. color = Color.red;
  31. else if (Mathf.Max(color.r, color.g, color.b) == color.g)
  32. color = Color.green;
  33. else
  34. color = Color.yellow;
  35. color *= 15f;
  36. GameObject spawned = GameObject.Instantiate(spawnObjectOnCollision);
  37. spawned.transform.position = contact.point;
  38. spawned.transform.forward = ray.direction;
  39. Renderer[] spawnedRenderers = spawned.GetComponentsInChildren<Renderer>();
  40. for (int rendererIndex = 0; rendererIndex < spawnedRenderers.Length; rendererIndex++)
  41. {
  42. Renderer spawnedRenderer = spawnedRenderers[rendererIndex];
  43. spawnedRenderer.material.color = color;
  44. if (spawnedRenderer.material.HasProperty("_EmissionColor"))
  45. {
  46. spawnedRenderer.material.SetColor("_EmissionColor", color);
  47. }
  48. }
  49. }
  50. }
  51. Debug.DrawRay(ray.origin, ray.direction, Color.cyan, 5, true);
  52. if (destroyOnTargetCollision)
  53. Destroy(this.gameObject);
  54. }
  55. }
  56. }
  57. }