Guest User

VRInteraction.cs

a guest
Feb 27th, 2016
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Main : MonoBehaviour {
  5.     //Constants
  6.     protected const float GAZE_LENGTH       = 100;
  7.     protected const float MAX_GAZE_DURATION = 2f;
  8.  
  9.     //Data
  10.     protected GameObject    mObject;
  11.     protected float         mGazeTime;
  12.  
  13.     void Start () {
  14.         //Initialize
  15.         mObject     = null;
  16.         mGazeTime   = 0;
  17.     }
  18.    
  19.     void Update () {
  20.         //Raycast from eye/camera, check if it hit something
  21.         RaycastHit hit;
  22.         if (Physics.Raycast(new Ray(transform.position, transform.forward), out hit, GAZE_LENGTH)) {
  23.             //If there's an object that was seen in the previous frame
  24.             if (mObject != null) {
  25.                 //If the same as current object
  26.                 if (mObject == hit.collider.gameObject) {
  27.                     //Increase gaze time
  28.                     mGazeTime += Time.deltaTime;
  29.                     if (mGazeTime > MAX_GAZE_DURATION) mGazeTime = MAX_GAZE_DURATION;
  30.  
  31.                     //Recolor
  32.                     float color = (MAX_GAZE_DURATION - mGazeTime) / MAX_GAZE_DURATION;
  33.                     ColorObject(mObject, new Color(1f, color, color));
  34.                 } else {
  35.                     //Reset old object since it's different
  36.                     ColorObject(mObject, Color.white);
  37.                     mGazeTime = 0;
  38.                 }
  39.             }
  40.  
  41.             //Save the object to variable
  42.             mObject = hit.collider.gameObject;
  43.  
  44.             //If object exists and mouse is clicked
  45.             if (mObject != null && Input.GetMouseButtonUp(0)) {
  46.                 //Move object elsewhere
  47.                 mObject.transform.position = new Vector3(Random.Range(-8, 8f), Random.Range(-2f, 2f), Random.Range(0, 3f));
  48.             }
  49.         } else {
  50.             //If there was an object
  51.             if (mObject != null) {
  52.                 //Reset
  53.                 ColorObject(mObject, Color.white);
  54.                 mGazeTime = 0;
  55.             }
  56.  
  57.             //No object was seen
  58.             mObject = null;
  59.         }
  60.     }
  61.  
  62.     protected void ColorObject(GameObject gameObject, Color color) {
  63.         //Skip if no object
  64.         if (gameObject == null) return;
  65.  
  66.         //Set material color
  67.         Renderer objectRenderer = gameObject.GetComponent<Renderer>();
  68.         if (objectRenderer != null) objectRenderer.material.color = color;
  69.     }
  70. }
Add Comment
Please, Sign In to add comment