Unity 3D : UI Image in the direction of a game object - user-interface

I'll explain my issue (My English is a little lame sorry).
I have a Player ( Camera) who is able to move in a Unity Scene. In this scene there is some GameObjects. Those GameObjects May be too far for the camera to see. What I want to achieve is to have an UI Image that appear in the direction of every objects. Even if the objects are too far.
Example : The player stand at a position. In front of him there is an object that is far. I want to have a GUI on screen who says "there is an object at 200 m ". If there is an object behind him I dont want anything to appear. But if he turns back, it will appear cause the player is in the direction of the said GameObject.
I really hope I made myself clear. Please tell me if you need any further explanations. Thank You community !

Answering to an old question of myself :
Here's what I did :
if (markIsOp) //Check if it's worth calculating
{
//Calculs the Viewport Position of the object
Vector3 ViewportPosition = Camera.main.WorldToViewportPoint (transform.position);
//Calculs it's Unity Canvas position (O.5f because UI anchor is middle)
Vector2 WorldObject_ScreenPosition = new Vector2 (
((ViewportPosition.x * mainCanvasRect.sizeDelta.x) - (mainCanvasRect.sizeDelta.x * 0.5f)),
((ViewportPosition.y * mainCanvasRect.sizeDelta.y) - (mainCanvasRect.sizeDelta.y * 0.5f)));
//Making sure it's forward (markRect is my UI Element's RectTransform)
if (ViewportPosition.z > 0)
markRect.anchoredPosition = WorldObject_ScreenPosition;
}
Thank you for your responses.
Have a nice one

You could as well use Camera.WorldToScreenPoint to calculate the "UI-Position" of your GameObjects and then calculate the distance using z-Coordinates of Gameobjects and Camera.

Use a raycast from the player to the game object, and calculate the difference.

Related

How to prevent object from flying towards camera when using Ray-cast in unity?

I got an unity project where object is meant to be moving with mouse cursor. The object moves fine, but when the object is still, it starts to float towards the camera that Ray-casts. I would like that the object doesn't float towards camera.
I couldn't find any reason for objects behavior.
I'm quite a novice who's had issues with gameobjects following cursors myself.
But could you try freezing the Y position in the Rigidbody and ensure gravity is unchecked?
More of a workaround if it even works.
Also I believe it's better practice to use rigidbody.position than transform.position. Try this:
public Rigidbody rigidbody;
void Update()
{
rigidbody.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -Camera.main.transform.position.z));
}
What is happening here is when you send a ray and you get a hit result using hit.point it gives the exact location of the tris on the object it is hitting. Lets say the object is centered in the world (Vector3.zero). Ray is hitting a tris that is different than the position zero. Just because the object is in x:0y:0z:0 doesnt mean all the tris on the object is located at the same coordinates.
You get the coordinates of the hit.point, they are probably closer than the object center position, therefore the object is updating its center position to the hit.point location. And it does that every frame moving the object closer to camera.
You might want to try sending a ray from screen to world position. You can use custom vector length which would help to keep the object in the same depth you like.
Unity Docs Screen to World

Why will my physics 2D raycast not display or work correctly?

Basically i wanted to make a raycast for jumping but for some reason the distance of the raycast is wrong and never changes and the position of it is so wrong i cant even seem to find it:
ray2D = Physics2D.Raycast(transform.position, -Vector2.up, .1f, GroundedLayers);
Debug.Log(ray2D.distance);
isGrounded = groundCheck();
Grounded layers do not include the player, distance always returns as 0, grounded is always false and the gizmos line only draws when i open the prefab and not at all in the scene:
here the distance is set to .1f but displays the same as 1f
(EDIT: ok so i checked and for some reason the raycast happens around 0, -1 even tho thats nowhere near the player transform?)
Try Vector2.down instead?
Alternative things to try:
Is the player in the scene the same as the prefab?
Increase the distance.
Add a new GameObject at the feet of the player, reference that in your script and call the Raycast from there.
Is ray2d a RayCastHit2d?
Are your ground object tags correct, including all grammer/caps?
Try outputting in debug, ray2d.collider.name to see what you're actually hitting.
If you're using a rigid body, try rigidbody2d. position instead of transform.position
Do you have the player selected in the hierarchy? This is needed to see the gizmos.
I found that the raycast was detecting an invisible trigger so i had to put it on another layer :)

How to fix Blue Screen appearing after GameObject is removed in Unity 2d Project

I have been successfully building and running a Unity 2D game, but started receiving a Blue Screen during one of my operations. Specifically, when I close a popup and remove all of its child Game Objects, the entire Game Screen turns dark blue (the default background color of the main camera). The music for the game still plays and clicks are still registered if you click in the right area (I can still press the back button, just can't see it).
If I remove 1 gameobject, this problem doesn't come up. But once I have to remove 2 game objects, the entire screen turns blue.
This is my function for removing my game object in case it helps, which works perfectly when it comes to actually removing the gameObjects correctly (game objects to be removed are created from prefabs). I think the problem may be with the camera for some reason, but I have no clue as to why it happens on this function.
public void Remove(int index)
{
float toggleWidth = toggle.GetComponent<RectTransform>().sizeDelta.x;
DestroyImmediate(scrollSnap.pagination.transform.GetChild(scrollSnap.NumberOfPanels - 1).gameObject);
scrollSnap.Remove(index);
scrollSnap.pagination.transform.position += new Vector3(toggleWidth / 2f, 0, 0);
}
I don't receive any errors or warnings in the console. Just a blue screen once more than one GameObject is removed
EDIT:
Turns out my main Canvas's planeDistance was being changed from 100 to 3200. I still have no clue as to why this change occurred...but for anyone else having a similar issue with a dark blue screen appearing in the middle or start of their game, then please check the values your canvas and camera in the Inspector. Simply controlling the planeDistance did the trick for me!
Made a new scene next to the sample scene when i started my sprite learning game. Forgot all about that.
When I had to publish it, In the Build Settings, I had the wrong scene selected. So It published an empty scene instead of my game.
I solved it by putting game in 3d mode and realized that the camera is positioned very far from the sprites, just change the z-axis and again go to 2d mode.
Just Move your camera in Z-axis position, it could be too far from object or it is behind the object, you can also check it by 3D mode the check the object position and change it in positive and negative values.

Unity 3D Kudan "Place Markerless Object" whenever mesh leaves screen?

I´m kinda new to Unity 3D and C#. Also i´m not exactly sure how Kudans arbitrary tracking solution works in detail. I´m currently using the Unity Kudan SDK to build a VR positional tracking solution, atleast i will try it. Now my plan is:
Whenever the mesh is leaving the screen, i want to freeze it´s position and find new feature points (the "place markerless object" button is doing this: Find new feature point and place a mesh).
Once it found new feature points (which should be a matter of milliseconds) it defreezes the position of the mesh and use the new feature points to further alter it´s position.
The "find new feature point" idea is necessary because whenever the mesh and the old feature points are leaving the screen, tracking will get very inaccurate.
I already tried this in SampleApp.cs:
bool VRSignal;
public void Start()
{
//Get Bools from "KudanTracker"
GameObject g = GameObject.Find("Kudan Camera");
KudanTracker bScript = g.GetComponent<KudanTracker>();
bool VRSignal = bScript.ArbiTrackIsTracking();
}
public void Update()
{
if(VRSignal == false)
{
// from the floor placer.
Vector3 floorPosition; // The current position in 3D space of the floor
Quaternion floorOrientation; // The current orientation of the floor in 3D space, relative to the device
_kudanTracker.FloorPlaceGetPose(out floorPosition, out floorOrientation); // Gets the position and orientation of the floor and assigns the referenced Vector3 and Quaternion those values
_kudanTracker.ArbiTrackStart(floorPosition, floorOrientation); // Starts markerless tracking based upon the given floor position and orientations
}
}
But now it won´t track properly track anymore, also i´m pretty sure ArbiTrackIsTracking() won´t be the solution for that because it won´t lose tracking when the mesh left the screen.
Do you have any idea to solve this problem?
if I understand well, you want change position of 3d model with trigger as soon as your 3d model disappear of the screen.
And you are right, ArbiTrackIsTracking() remain true even if the 3d model go out the screen because if you move again your screen around the 3d model, the 3d model will be always tracked.
But if you move too much your smartphone logically the tracking stops.
My idea for your issue is to get the position of your 3d model markerless transform driver, because the 3d model moves in function the position and orientation of your smartphone to track.
So you can take the position of the moment where your 3d model begin to be tracked.
Then you give a value who will correspond to the difference of first and last position saved.
And if this difference is get, you stop the tracking with arbitrack stop.
if you have another question you can ask on my twitter account #ModeLolito I could answer faster.
And you can watch my youtube channel to see my works on kudan
https://www.youtube.com/user/modelisationLolito

Unity3d. How to get screen or world position of ui element

I have UI elements (image, etc). Canvas attached to camera.
There is a RectTransform, but how to convert this data to screen or world coordinates and get center point of this image?
Tried RectTransform.GetWorldCorners but it returns zero vectors.
yourRectTransform.rect.center for the centre point in local space.
yourRectTransform.TransformPoint to convert to world space.
It is odd that RectTransform.GetWorldCorners doesn't work as stated. Per one of the other answers you need to call after Awake (so layout can occur).
I found that both GetWorldCorners and TransformPoint only work on Start(), not on Awake(), as if we'll have to wait for the content to be resized
Vector3 min = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.min);
Vector3 max = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.max);
elementToResize.transform.localScale = new Vector3(Mathf.Abs(min.x - max.x) , Mathf.Abs(min.y - max.y), 1f);
elementToResize.transform.position = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.center);
You can work with GetWorldCorners but only when using a child that has real dimensions. I got reasonable values for a child of a world space canvas.
Following Huacanacha's guidance,
Vector2 _centerPosition = _rectTransform.TransformPoint(_rectTransform.rect.center);
will give you the WorldCoordinate of the center of the image.

Resources