- Home /
Camera Viewport detecting objects behind
Hello Everybody,
I am trying to mark on my Canvas usable points for the player when they click and hold the right mouse button. I calculated the position of the UI elements using @Sylos solution from this thread, but the system is also rendering the points that are behind the player. (Purple circles show correct, and red show the "phantom" ones) Higher resolution
The code I'm using looks exactly like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GraplingHookPoints : MonoBehaviour {
public GameObject m_Prefab;
public Camera m_Cam;
public GameObject m_CanvasRef;
public RectTransform m_CanvasRect;
public List<Transform> m_HookPoints;
public List<GameObject> m_HookPointIcons;
private bool isInitialized = false;
bool isShowing = false;
Transform m_T;
Vector2 m_ViewportPosition;
Vector2 m_WorldObjScreenPos;
// Use this for initialization
public void Initialize () {
foreach(Transform t in m_HookPoints)
{
m_HookPointIcons.Add(Instantiate(m_Prefab, m_CanvasRef.transform.position, m_CanvasRef.transform.rotation, m_CanvasRef.transform));
}
foreach (GameObject go in m_HookPointIcons)
{
go.SetActive(false);
}
m_CanvasRect = m_CanvasRef.GetComponent<RectTransform>();
isInitialized = true;
}
// Update is called once per frame
void Update () {
if (!isInitialized)
return;
if (Input.GetMouseButtonDown(1))
{
ShowHookPoints(true);
}
if (isShowing)
UpdateIconPosition();
if (Input.GetMouseButtonUp(1))
{
ShowHookPoints(false);
}
}
private void ShowHookPoints(bool isShowingIcons)
{
foreach (GameObject go in m_HookPointIcons)
{
go.SetActive(isShowingIcons);
}
isShowing = isShowingIcons;
}
private void ShowHookPoint(GameObject hp, bool show)
{
hp.SetActive(show);
}
private void UpdateIconPosition()
{
for (int i = 0; i < m_HookPoints.Count; i++)
{
m_T = m_HookPoints[i];
m_ViewportPosition = m_Cam.WorldToViewportPoint(m_T.position);
m_WorldObjScreenPos = new Vector2(((m_ViewportPosition.x * m_CanvasRect.sizeDelta.x) - (m_CanvasRect.sizeDelta.x *0.5f)), ((m_ViewportPosition.y * m_CanvasRect.sizeDelta.y) - (m_CanvasRect.sizeDelta.y * 0.5f)));
m_HookPointIcons[i].GetComponent<RectTransform>().anchoredPosition = m_WorldObjScreenPos;
}
}
}
Can anybody advise me on how to make sure that it displays only the icons for the objects on screen, please? N.B. the objects being "traced" have no mesh on them, just a sphere collider
Thank you in advance for all the help!
Your answer
Follow this Question
Related Questions
How to fit a camera Viewport Rect to a UI Panel 1 Answer
Scroll view/rect broken on Android only 0 Answers
The most generic way to change ViewPort 0 Answers
Force UIImage to stay on viewport? 0 Answers
Can I combine 2 or more UI masks? 0 Answers