Untitled
unknown
plain_text
3 days ago
3.7 kB
8
Indexable
using UnityEngine;
using System.Collections;
using perfectbloo.GpuRaycast;
using perfectbloo.Core;
public class GunRaycastPlugin : MVRScript
{
private ScenePlugin<GpuRaycastApi> gpuRaycast = new ScenePlugin<GpuRaycastApi>(
GpuRaycastApi.Author,
GpuRaycastApi.PackageName,
GpuRaycastApi.PluginName,
GpuRaycastApi.ScriptName
);
private LineRenderer _line;
public override void Init()
{
SuperController.LogMessage("Gun plugin loaded");
JSONStorableAction shootAction = new JSONStorableAction("Shoot", Shoot);
RegisterAction(shootAction);
// Visual beam setup
GameObject lineObj = new GameObject("GunBeam");
_line = lineObj.AddComponent<LineRenderer>();
_line.material = new Material(Shader.Find("Sprites/Default"));
_line.startColor = Color.yellow;
_line.endColor = new Color(1f, 0.9f, 0f, 0f);
_line.startWidth = 0.015f;
_line.endWidth = 0.015f;
_line.useWorldSpace = true;
_line.positionCount = 2;
_line.enabled = false;
SuperController.LogMessage("Gun loaded. Ready to shoot");
}
void Shoot()
{
SuperController.LogMessage("Raycast Triggered: Firing");
if (gpuRaycast.Api == null)
{
SuperController.LogMessage("GPU Raycast API missing!");
return;
}
// flash
StopAllCoroutines();
StartCoroutine(ShootCoroutine());
}
private IEnumerator ShootCoroutine()
{
yield return new WaitForEndOfFrame();
Vector3 rayOrigin = containingAtom.mainController.transform.position + containingAtom.mainController.transform.forward * 0.1f;
Vector3 direction = containingAtom.mainController.transform.forward;
float maxDistance = 1000f;
int layerMask = 1;
GpuRaycastHit hit;
Vector3 endPoint;
SuperController.LogMessage($"rayOrigin: {rayOrigin.ToString("F3")}");
SuperController.LogMessage($"Direction: {direction.ToString("F3")}");
try
{
// 1000f is the max distance, 29 is the 'Atoms' layer in VaM
if(gpuRaycast.Api.Raycast(rayOrigin, direction, out hit, maxDistance, layerMask)==true)
{
// Log if it successfully hit a person
SuperController.LogMessage("Result: HIT! -> " + (hit.Atom != null ? hit.Atom.name : "Something"));
endPoint = hit.Point;
OnPersonHit(hit);
}
else
{
// Log if it hit nothing or hit something that wasn't a person
SuperController.LogMessage("Result: MISS!");
endPoint = rayOrigin + (direction * maxDistance);
}
}
catch (System.Exception e)
{
SuperController.LogMessage("GPU Raycast Crash: " + e.Message);
endPoint = rayOrigin + (direction * maxDistance);
}
StartCoroutine(FlashBeam(rayOrigin, endPoint));
}
IEnumerator FlashBeam(Vector3 startPos, Vector3 endPos)
{
_line.enabled = true;
float elapsed = 0f;
float duration = 0.1f;
while (elapsed < duration)
{
_line.SetPosition(0, startPos);
_line.SetPosition(1, endPos);
elapsed += Time.deltaTime;
yield return null;
}
_line.enabled = false;
}
void OnPersonHit(GpuRaycastHit hit)
{
if (hit.Atom != null) SuperController.LogMessage("Hit Atom: " + hit.Atom.name);
}
}Editor is loading...
Leave a Comment