Cannot make a Rectangle to display with Unity + Oculus Rift - c#

I'm trying to display a simple rectangle right in front of my OVRPlayerController's camera but it seems to be impossible.
I think it might have something to do with the fact that Rect is 2D and my environment is 3D. Does that make sense?
The code is the following (I have ommited the unnecessary stuff):
static int MAX_MENU_OPTIONS = 3;
public GameObject Menu;
private bool showMenu = false;
private float menuIndex = 0;
private bool hasPressedDirectionalPad = false;
public Transform[] buttons = new Transform[MAX_MENU_OPTIONS];
private static Texture2D staticRectTexture;
private static GUIStyle staticRectStyle;
bool DpadIsPressed() {
if (!hasPressedDirectionalPad && Input.GetAxis("DpadY") != 0 && hasPressedDirectionalPad == false){
menuIndex += Mathf.Sign(Input.GetAxis("DpadY")) * (-1);
if (menuIndex < 0) menuIndex = 0;
else if (menuIndex > MAX_MENU_OPTIONS-1) menuIndex = MAX_MENU_OPTIONS-1;
hasPressedDirectionalPad = true;
}
if(Input.GetAxis("DpadY") == 0){
hasPressedDirectionalPad = false;
}
return hasPressedDirectionalPad;
}
void Start() {
Menu.SetActive(false);
staticRectTexture = new Texture2D(1, 1, TextureFormat.RGB24, true);
staticRectStyle = new GUIStyle();
}
void Update() {
if (Input.GetButtonDown("A")) {
DoAction ();
print ("A key was pressed");
}
if (Input.GetButtonDown("Options")) {
showMenu = !showMenu;
if (showMenu) {
Time.timeScale = 0;
menuIndex = 0;
Menu.transform.rotation = this.transform.rotation;
Menu.transform.position = this.transform.position;
} else
Time.timeScale = 1;
}
if (DpadIsPressed ()) {
print ("Dpad key was pressed and menuIndex = " + menuIndex);
}
if (showMenu) {
Menu.SetActive (true);
}
if (!showMenu) {
Menu.SetActive (false);
}
}
void OnGUI() {
if (showMenu) {
Vector3 offset = new Vector3(0, 0, 0.2f);
Vector3 posSelectRectangle = buttons[(int)menuIndex].transform.position + offset;
Rect selectionRectangle = new Rect(posSelectRectangle.x - (float)177/2,
posSelectRectangle.y - (float)43/2,
177.0f, 43.0f);
GUIDrawRect(selectionRectangle, new Color(255.0f, 0, 0));
}
}
void DoAction () {
if (menuIndex == 0)
Salir ();
/*else if (menuIndex == 1)
Guardar ();*/
else if (menuIndex == 2)
Salir ();
}
public static void GUIDrawRect(Rect position, Color color ) {
staticRectTexture.SetPixel( 0, 0, color );
staticRectTexture.Apply();
staticRectStyle.normal.background = staticRectTexture;
GUI.Box( position, GUIContent.none, staticRectStyle );
}
The functions are visited, but the rectangle doesn't show up. Do you see the mistake? Maybe it has something to do with the Oculus Rift?

OnGUI and Screen-space Canvas are not supported in VR mode. This is because there is no way to handle stereoscopic rendering. (Note: They will render to the duplicate display on the user's PC though).
If you want to render in front of the user's camera (like a HUD), you can:
Use a Canvas:
Create a canvas, then add your UI, and set the canvas in world-space. Parent the canvas to the VR Camera game object, and scale it down (it defaults to very very big) and rotate it so it faces the camera.
Or, Use 3D:
Create a 3d Object (Plane, Cube, Quad, whatever!) and parent it to your VR Camera. You can use standard 3d techniques to update it's texture or render texture.

Related

how to show next image in a carousel view in c#?

I am creating a carousel view with next and previous buttons to show the previous and next images. When I am clicking the Next button it doesn't get to next image, it stays the same. Can anyone help me solve this issue.
Here is what I've tried so far:
// Declare variables.
public RectTransform window;
public bool startWelcomeScreen;
public RectTransform[] introImages;
private float wide;
private float mousePositionStartX;
private float mousePositionEndX;
private float dragAmount;
private float screenPosition;
private float lastScreenPosition;
private float lerpTimer;
private float lerpPage;
public int pageCount = 1;
public string side = "";
public int swipeThrustHold = 30;
public int spaceBetweenProfileImages = 30;
private bool canSwipe;
public GameObject cartoonWindow;
public Texture2D userPic;
void Start() {
wide = cartoonWindow.GetComponent<RectTransform>().rect.width;
for(int i = 1; i < introImages.Length; i++){
introImages[i].anchoredPosition = new Vector2(((wide+spaceBetweenProfileImages)*i),0);
}
side = "right";
startWelcomeScreen = true;
}
public void NextButtonIsTapped()
{
cartoonWindow.SetActive(true);
}
void Update() {
if(!startWelcomeScreen)
return;
lerpTimer=lerpTimer+Time.deltaTime;
if(lerpTimer<.333){
screenPosition = Mathf.Lerp(lastScreenPosition ,lerpPage*-1 , lerpTimer*3);
lastScreenPosition=screenPosition;
}
if(Input.GetMouseButtonDown(0) && Input.mousePosition.y > (Screen.height*0.6173f) && Input.mousePosition.y < (Screen.height*0.91f) ) {
canSwipe = true;
mousePositionStartX = Input.mousePosition.x;
}
if(Input.GetMouseButton(0)) {
if(canSwipe){
mousePositionEndX = Input.mousePosition.x;
dragAmount=mousePositionEndX-mousePositionStartX;
screenPosition=lastScreenPosition+dragAmount;
}
}
if(Mathf.Abs(dragAmount) > swipeThrustHold && canSwipe){
canSwipe = false;
lastScreenPosition=screenPosition;
if(pageCount < introImages.Length )
OnSwipeComplete () ;
else if(pageCount == introImages.Length && dragAmount < 0)
lerpTimer=0;
else if(pageCount == introImages.Length && dragAmount > 0)
OnSwipeComplete () ;
}
if(Input.GetMouseButtonUp(0)) {
if(Mathf.Abs(dragAmount) < swipeThrustHold) {
lerpTimer = 0;
}
}
for(int i = 0; i < introImages.Length; i++){
introImages[i].anchoredPosition = new Vector2(screenPosition+((wide+spaceBetweenProfileImages)*i),0);
if(side == "right") {
if(i == pageCount-1) {
introImages[i].localScale = Vector3.Lerp(introImages[i].localScale,new Vector3(1.2f,1.2f,1.2f),Time.deltaTime*5);
Color temp = introImages[i].GetComponent<Image>().color;
introImages[i].GetComponent<Image>().color = new Color(temp.r,temp.g,temp.b,1);
} else {
introImages[i].localScale = Vector3.Lerp(introImages[i].localScale,new Vector3(0.7f,0.7f,0.7f),Time.deltaTime*5);
Color temp = introImages[i].GetComponent<Image>().color;
introImages[i].GetComponent<Image>().color = new Color(temp.r,temp.g,temp.b,0.5f);
}
} else {
if(i == pageCount) {
introImages[i].localScale = Vector3.Lerp(introImages[i].localScale,new Vector3(1.2f,1.2f,1.2f),Time.deltaTime*5);
Color temp = introImages[i].GetComponent<Image>().color;
introImages[i].GetComponent<Image>().color = new Color(temp.r,temp.g,temp.b,1);
} else {
introImages[i].localScale = Vector3.Lerp(introImages[i].localScale,new Vector3(0.7f,0.7f,0.7f),Time.deltaTime*5);
Color temp = introImages[i].GetComponent<Image>().color;
introImages[i].GetComponent<Image>().color = new Color(temp.r,temp.g,temp.b,0.5f);
}
}
}
}
#endregion
I don't get any errors though but it's just don't get to next image.
Looking at the code above I would suggest you create a parent gameobject around the introImages and rather move it's anchored position and not move each image. By moving the anchored position of the parent, all the child images will move within the mask.
To include paging buttons to move next and previous, you could do:
void Start () {
rectTransform = sliderWrapper.GetComponent<RectTransform> (); // parent wrapper
currentItem = 0; // start x position of the wrapper
itemWidth = 1000f; // width of the images
itemCount = sliderWrapper.transform.childCount; // number of images
}
Then in your next and previous methods, you move the parent's anchoredPosition:
public void Next () {
currentItem++; // the next image
rectTransform.anchoredPosition = new Vector2 (-currentItem * itemWidth, 0); // move the x position by the currentItem (the index) multiplied by image width
prevButton.interactable = true;
if (currentItem == itemCount - 1) {
nextButton.interactable = false;
}
}
public void Prev () {
currentItem--; // previous image
rectTransform.anchoredPosition = new Vector2 (-currentItem * itemWidth, 0); // move the x position by the currentItem (the index) multiplied by image width
if (currentItem == 0) {
prevButton.interactable = false;
}
if (currentItem < itemCount) {
nextButton.interactable = true;
}
}
UPDATE
Some steps to help outline the above. Note no animation is in place, it simply jumps to the relevant slider item.
1) Add a GameObject, called Slider below, with a Rect Mask 2D component and set the rect transform width/height to match a single image's width/height. This will mask out the overflowing children.
2) Add a GameObject, called Item Wrapper below, with a Horizontal Layout Group component and a Content Size Fitter and set properties like below to allow it to scale the game object's rect transform width according to the children and also layout the images horizontally:
Now all you need to do is update the Slider Wrapper's anchoredPosition. This will move the wrapper within the parent Slider GameObject. As the Slider GameObject has a mask on it, we don't see any of the overflowing items.
[SerializeField]
Button nextButton;
[SerializeField]
Button prevButton;
[SerializeField]
GameObject sliderWrapper;
float itemWidth;
int itemCount;
int currentItem;
RectTransform rectTransform;
void Start () {
rectTransform = sliderWrapper.GetComponent<RectTransform> ();
currentItem = 0;
itemWidth = 1000f; // width of your slider/image
itemCount = sliderWrapper.transform.childCount;
}
public void Next () {
currentItem++;
rectTransform.anchoredPosition = new Vector2 (-currentItem * itemWidth, 0);
prevButton.interactable = true;
if (currentItem == itemCount - 1) {
nextButton.interactable = false;
}
}
public void Prev () {
currentItem--;
rectTransform.anchoredPosition = new Vector2 (-currentItem * itemWidth, 0);
if (currentItem == 0) {
prevButton.interactable = false;
}
if (currentItem < itemCount) {
nextButton.interactable = true;
}
}
BONUS
Code to animate the slider:
public void Next () {
currentItem++;
prevButton.interactable = false;
nextButton.interactable = false;
StartCoroutine (SlideTo (new Vector2 (-currentItem * itemWidth, 0), () => {
prevButton.interactable = true;
if (currentItem < itemCount - 1) {
nextButton.interactable = true;
}
}));
}
public void Prev () {
currentItem--;
prevButton.interactable = false;
nextButton.interactable = false;
StartCoroutine (SlideTo (new Vector2 (-currentItem * itemWidth, 0), () => {
if (currentItem > 0) {
prevButton.interactable = true;
}
if (currentItem < itemCount) {
nextButton.interactable = true;
}
}));
}
IEnumerator SlideTo (Vector2 position, Action callback = null, float timeToMove = .5f) {
var t = 0f;
while (t < 1) {
t += Time.deltaTime / timeToMove;
rectTransform.anchoredPosition = Vector2.Lerp (rectTransform.anchoredPosition, position, t);
yield return new WaitForEndOfFrame ();
}
if (callback != null) {
callback ();
}
}

Enable and disable Renderer or Canvas not working

Every 5 seconds I need to take a photo and display it in the world. That part is working fine.
Once a photo is taken it need to disappear 1 second after. That's where I'm stuck.
I've gotten it to disappear but then I cant get the new picture to reappear when its function is called again.
Any ideas?
I've tried:
m_CanvasRenderer.enabled = false;
m_CanvasRenderer.enabled = true;
m_Canvas = null;
m_Canvas.setActive(false);
m_Canvas.setActive(true);
With no luck
public class PhotoCaptureExample : MonoBehaviour
{
GestureRecognizer m_GestureRecognizer;
GameObject m_Canvas = null;
Renderer m_CanvasRenderer = null;
PhotoCapture m_PhotoCaptureObj;
CameraParameters m_CameraParameters;
bool m_CapturingPhoto = false;
Texture2D m_Texture = null;
void Start()
{
Initialize();
InvokeRepeating("TakePhoto", 5.0f, 5.0f);
//StartCoroutine(TakePhoto());
}
void TakePhoto()
{
if (m_CapturingPhoto)
{
return;
}
m_CapturingPhoto = true;
m_PhotoCaptureObj.TakePhotoAsync(OnPhotoCaptured);
}
void OnPhotoCaptured(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
{
// m_CanvasRenderer.enabled = true;
if (m_Canvas == null)
{
m_Canvas = GameObject.CreatePrimitive(PrimitiveType.Quad);
m_Canvas.name = "PhotoCaptureCanvas";
m_CanvasRenderer = m_Canvas.GetComponent<Renderer>() as Renderer;
m_CanvasRenderer.material = new Material(Shader.Find("AR/HolographicImageBlend"));
}
Matrix4x4 cameraToWorldMatrix;
photoCaptureFrame.TryGetCameraToWorldMatrix(out cameraToWorldMatrix);
Matrix4x4 worldToCameraMatrix = cameraToWorldMatrix.inverse;
Matrix4x4 projectionMatrix;
photoCaptureFrame.TryGetProjectionMatrix(out projectionMatrix);
photoCaptureFrame.UploadImageDataToTexture(m_Texture);
m_Texture.wrapMode = TextureWrapMode.Clamp;
m_CanvasRenderer.sharedMaterial.SetTexture("_MainTex", m_Texture);
m_CanvasRenderer.sharedMaterial.SetMatrix("_WorldToCameraMatrix", worldToCameraMatrix);
m_CanvasRenderer.sharedMaterial.SetMatrix("_CameraProjectionMatrix", projectionMatrix);
m_CanvasRenderer.sharedMaterial.SetFloat("_VignetteScale", 1.0f);
// Position the canvas object slightly in front
// of the real world web camera.
Vector3 position = cameraToWorldMatrix.GetColumn(3) - cameraToWorldMatrix.GetColumn(2);
// Rotate the canvas object so that it faces the user.
Quaternion rotation = Quaternion.LookRotation(-cameraToWorldMatrix.GetColumn(2), cameraToWorldMatrix.GetColumn(1));
m_Canvas.transform.position = position;
m_Canvas.transform.rotation = rotation;
m_CapturingPhoto = false;
float counter = 0; float target = 1;
while (counter < target)
{
counter += Time.deltaTime;
}
// m_CanvasRenderer.enabled = false;
}
}

Unity: Cant switch a scroll panel to vertical instead of horizontal?

Ok, I am having a problem with a Unity scroll panel in C#. I downloaded this character picker that consists of a script attached to a scroll panel from here:
https://www.youtube.com/watch?v=YBsGhYuTavA
It works very well but problem is I cant make it scroll vertically instead of horizontal. I have checked the "vertical" boolean instead of horizontal on the actual scroll panel then in the script I have changed the places that based off x values to y values.
I commented where, here is the script:
float[] distance;
bool dragging = false;
int minButtonNum;
int currentSelectedPly = -1;
public float objectScale = 1.7f;
public int bttnDistance = 300;
void OnEnable() {
//txtGeneralCash.text = "" + PlayerPrefs.GetInt ("money", 0);
}
void Start(){
distance = new float[prefab.Length];
//instatiate the prefab
for(int i=0; i<prefab.Length;i++){
prefab[i] = Instantiate(prefab[i],center.transform.position,camInUse.transform.rotation) as GameObject;
prefab [i].transform.SetParent(panel.transform);
Vector3 pos = prefab[i].GetComponent<RectTransform>().anchoredPosition;
pos.x += (i * bttnDistance); //**CHANGED TO POS.Y
prefab [i].GetComponent<RectTransform> ().anchoredPosition = pos;
}
}
void Update(){
//calculate the relative distance
for(int i=0;i<prefab.Length;i++){
distance [i] = Mathf.Abs (center.transform.position.x - prefab [i].transform.position.x); //CHANGED THESE TO .Y
}
float minDistance = Mathf.Min (distance);
// Aplly the scale to object
for(int a=0;a<prefab.Length;a++){
if (minDistance == distance [a]) {
minButtonNum = a;
//this is when each char is selected !!!!!!!!!!!!!!!
if(minButtonNum != currentSelectedPly){
//lookAtPrice (minButtonNum);
scaleButtonCenter (minButtonNum);
currentSelectedPly = minButtonNum;
txtName.text = prefab [minButtonNum].GetComponent<CharacterProperty> ().nameObj;
bgMat.color = prefab [minButtonNum].GetComponent<CharacterProperty> ().color;
}
}
}
// if the users aren't dragging the lerp function is called on the prefab
if(!dragging){
LerpToBttn (currentSelectedPly* (-bttnDistance));
}
}
/*
* Lerp the nearest prefab to center
*/
void LerpToBttn(int position){
float newX = Mathf.Lerp (panel.anchoredPosition.x,position,Time.deltaTime*7f); //CHANGED TO .Y
Vector2 newPosition = new Vector2 (newX,panel.anchoredPosition.y);
panel.anchoredPosition = newPosition;
}
/*
* Set the scale of the prefab on center to 2, other to 1
*/
public void scaleButtonCenter (int minButtonNum){
for (int a = 0; a < prefab.Length; a++) {
if (a == minButtonNum) {
StartCoroutine (ScaleTransform(prefab [a].transform,prefab [a].transform.localScale,new Vector3 (objectScale,objectScale,objectScale)));
} else {
StartCoroutine (ScaleTransform(prefab [a].transform,prefab [a].transform.localScale,new Vector3 (1f, 1f, 1f)));
}
}
}
/*
* If the prefab is not free, show the price button
/*
* Courutine for change the scale
*/
IEnumerator ScaleTransform(Transform transformTrg,Vector3 initScale,Vector3 endScale){
float completeTime = 0.2f;//How much time will it take to scale
float currentTime = 0.0f;
bool done = false;
while (!done){
float percent = currentTime / completeTime;
if (percent >= 1.0f){
percent = 1;
done = true;
}
transformTrg.localScale = Vector3.Lerp(initScale, endScale, percent);
currentTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
}
/*
* Called by the canvas, set dragging to true for preventing lerp when users are dragging
*/
public void StartDrag(){
dragging = true;
}
/*
* Called by the canvas, set dragging to true for preventing lerp when users are dragging
*/
public void EndDrag(){
dragging = false;
}
/*
* Called when character is selected, it change the player model
*/
public void CharacterSelected(){
bool oneEnable = false;
string nameSelected = prefab [currentSelectedPly].GetComponent<CharacterProperty> ().name;
nameSelected = nameSelected.Split('(')[0];
GameObject player = GameObject.Find ("CharactersPlayer");
if(player != null){
foreach (Transform child in player.transform) {
if (child.gameObject.name == nameSelected) {
child.gameObject.SetActive (true);
oneEnable = true;
PlayerPrefs.SetString ("SelectedPlayer", nameSelected);
} else {
child.gameObject.SetActive (false);
}
}
// if no one was selected
if (oneEnable == false) {
player.transform.GetChild (0).gameObject.SetActive (true);
}
}
}
Ive gone through it several times and I don't know why just changing the values from .x to .y does not work. I get a bunch of glitching and the characters do stack up vertically, but they move off the screen when i try to scroll.
How can I fix this?

UI Panel Lerp Update

I have a couple of UI Panels that I wish to move into the screen area.
I have made a script to attach to each Panel but it does little when I do my changes in Update which I am now using LateUpdate instead which almost works.
The panel will move into the screen only very slightly as if LateUpdate was called only once.
Oddly, when I do the same with a second Panel, it's 'HidePanel' method then lets the first Panel come fully into view. Then the first Panel's 'HidePanel' method works correctly.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DisplayPanel : MonoBehaviour {
private bool isMovingIn = false;
private bool isMovingOut = false;
private Vector2 posOut; //The panel's position hidden just outside the RH screen edge.
private Vector2 posIn; //The panel’s position shown just inside the RH screen edge.
private Vector2 pos; //The panel’s current position.
//Initialization
void Start () {
RectTransform rt = GetComponent<RectTransform>();
posOut = new Vector2 ((Screen.width + rt.rect.width)/2, 0); //To be hidden just outside the RH screen edge.
posIn = new Vector2 (posOut.x - rt.rect.width, 0); //To be visible just inside the RH screen edge.
pos = posOut;
rt.anchoredPosition = pos; //Move panel to the RH screen edge.
}
public void LateUpdate() {
RectTransform rt = GetComponent<RectTransform> ();
rt.anchoredPosition = pos; //Need this for start..
if (isMovingIn == true) {
if ((int)pos.x != (int)posIn.x) { //Casting floats to ints so we can eventually find equality.
pos = Vector2.Lerp (pos, posIn, 2*Time.deltaTime);
rt.anchoredPosition = pos;
}
else {
isMovingIn = false; }
}
else
if (isMovingOut == true) {
if ( (int)pos.x != (int)posOut.x) {
pos = Vector2.Lerp (pos, posOut, 2 * Time.deltaTime);
rt.anchoredPosition = pos; }
else {
isMovingOut = false; }
}
}
public void DisplayPanel(){
isMovingOut = false;
isMovingIn = true;
}
public void HidePanel(){
isMovingIn = false;
isMovingOut = true;
}
}//End class

Why does this strange jittering occur?

I have a scene in which the player can pick up and drop objects, as well as move and look around.
All player objects are children of an empty game object "MainCharacter":
MainCharacter >
Capsule (With RigidBody and PlayerMoveScript) >
PlayerBase (empty - used for checking if grounded)
MainCamera >
Hands(With PickUpDrop script)
The object I pick up Lerps to my Hands position, however after my capsule collides with any walls there is a strange jittering which I cannot work out how to fix!!
Heres the .exe:GameTest
Heres the data folder : Data
Here are the scripts:
Pick Up and Drop Script:
public bool handsFull = false;
public float distanceMax = 20f;
public Transform handPosition;
public LayerMask canPickUp;
public GameObject taggedGameObject;
public bool colliderTriggered;
public bool bounds;
public PickedUpObject pickedUpScript;
public Rigidbody player;
// Use this for initialization
void Start () {
print(FindClosestPickup().name);
handPosition = transform;
pickedUpScript = null;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.E) && !bounds) {
if (Physics.CheckSphere (handPosition.position, 2f, canPickUp)) {
if (handsFull) {
Drop ();
}
if (!handsFull) {
PickedUp ();
}
handsFull = !handsFull;
}
}
if (handsFull) {
RotateMovePickedUpObject();
}
}
private void PickedUp(){
//Closest object to top of list
taggedGameObject = (GameObject)FindClosestPickup();
taggedGameObject.collider.isTrigger = true;
taggedGameObject.rigidbody.useGravity = false;
taggedGameObject.rigidbody.isKinematic = true;
pickedUpScript = taggedGameObject.GetComponent<PickedUpObject> ();
Debug.Log ("Pick Up");
}
private void RotateMovePickedUpObject(){
//Rotate
if(Input.GetKeyDown(KeyCode.End)){
taggedGameObject.transform.localRotation *= Quaternion.Euler(0, 0, 45);
}
if(Input.GetKeyDown(KeyCode.Delete)){
taggedGameObject.transform.localRotation *= Quaternion.Euler(0, 45, 0);
}
if(Input.GetKeyDown(KeyCode.PageDown)){
taggedGameObject.transform.localRotation *= Quaternion.Euler(0, -45, 0);
}
if(Input.GetKeyDown(KeyCode.Home)){
taggedGameObject.transform.localRotation *= Quaternion.Euler(0, 0, -45);
}
if(Input.GetKeyDown(KeyCode.PageUp)){
taggedGameObject.transform.localRotation *= Quaternion.Euler(-45, 0, 0);
}
if(Input.GetKeyDown(KeyCode.Insert)){
taggedGameObject.transform.localRotation *= Quaternion.Euler(45, 0, 0);
}
taggedGameObject.transform.position = Vector3.Lerp(taggedGameObject.transform.position, handPosition.position, (1 - Mathf.Exp( -20 * Time.smoothDeltaTime )) * 10);
}
private void Drop(){
taggedGameObject.collider.isTrigger = false;
taggedGameObject.rigidbody.useGravity = true;
taggedGameObject.rigidbody.isKinematic = false;
taggedGameObject = null;
Debug.Log ("Drop");
pickedUpScript = null;
}
private GameObject FindClosestPickup() {
//Find closest gameobject with tag
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("pickup");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
}
The Picked Up Objects Script:
public PickUpDrop pickUpScript;
public GameObject thisOne;
public Color thecolor;
public bool inObject;
// Use this for initialization
void Start () {
thisOne = this.gameObject;
}
// Update is called once per frame
void Update ()
{
thecolor = thisOne.renderer.material.color;
if (pickUpScript.taggedGameObject != thisOne)
{
gameObject.renderer.material.color = Color.gray;
}
if (pickUpScript.taggedGameObject == thisOne)
{
Color color = renderer.material.color;
color.a = 0.5f;
renderer.material.color = color;
}
}
void OnTriggerEnter ()
{
if (thisOne == pickUpScript.taggedGameObject)
{
inObject = true;
pickUpScript.bounds = true;
gameObject.renderer.material.color = Color.red;
}
}
void OnTriggerExit()
{
if(thisOne == pickUpScript.taggedGameObject)
{
inObject = false;
pickUpScript.bounds = false;
gameObject.renderer.material.color = Color.gray;
}
}
}
taggedGameObject.transform.position = Vector3.Lerp(taggedGameObject.transform.position, handPosition.position, (1 - Mathf.Exp( -20 * Time.smoothDeltaTime )) * 10);
This line will keep moving the object towards the hand's position. If you have a rigidbody attached to the game object you're moving then the physics acting on that object during the physics calculation will conflict with the manual movement of the object during the Update function.
It depends on what you would like to happen when this conflict occurs as to the solution. If you simply want the 'jittering' to stop and still be able to hold objects against other physical objects, then use this;
taggedGameObject.rigidbody.AddForce( ( taggedGameObject.transform.position - handPosition.position ) * force );
This will keep all interactions with the rigidbody. You'll have to tweak the force you move the object with, and perhaps disable gravity on the tagged game object while it's in the players hands. But it should have the desired effect.

Categories

Resources