Hi, I’m new to Unity and I’m learning to create some scripts at the same time. I’m developing an application using the Oculus Rift and I’m trying to do something with raycasts: In my scene, I have several gameObjects in front of my camera and I have a raycast with my camera as its origin.
What I want to do is, when the user looks at the object (so the ray hits the object), the object moves to a position but when the object is no longer raycasted (the user looks somewhere else), the object returns to its original position.
If that helps, I have this script on my camera to move to a position when I start the scene:
using UnityEngine;
using System.Collections;
public class MovementC : MonoBehaviour {
public Vector3 endPoint;
public float duration = 1.0f;
private Vector3 startPoint;
private float startTime;
// Use this for initialization
void Start () {
startPoint = transform.position;
startTime = Time.time;
}
// Update is called once per frame
void Update () {
transform.position = Vector3.Lerp(startPoint, endPoint, (Time.time - startTime)/duration);
}
}
not going to work it out completely but what about
//object currently being looked at
GameObject lookAt;
//previous position of looked-at object
Vector3 prevPos;
//point where we move an object we look at
Vector3 newPos;
void Update {
RaycastHit hit;
//too lazy to define the look ray here
if(Physics.Raycast(ray, out hit)){
//if not currently looking at something
if(lookAt == null){
//look at the hit object
lookAt = hit.transform.root.gameObject;
//store its position
prevPos = lookAt.transform.position;
//move it to the new position
lookAt.transform.position = newPos;
}
//if not looking at something and we still have a lookat object stored
}else if(lookAt != null){
///put it back
lookAt.transform.position = prevPos;
//set curretn lookAt to null
lookAt = null;
}
}
One major problem with this script occurs when you look at another object without looking at ‘nothing’ in between, but that is easy to fix, just put some condition in the raycast-if like if(hit.transform.root.gameObject != lookAt), you basically do the same to the current (‘old’) one as when you no longer look at something and then set the one you are looking at now as the current one.