繁体   English   中英

如何从世界空间中找到 Object 的 position 并转换为具有渲染模式的 Canvas UI:屏幕空间 - Unity 2d 中的相机?

[英]how to find a position of an Object from World Space and convert to Canvas UI with render mode : Screen Space - Camera in Unity 2d?

我正在从事与马里奥非常相似的游戏。 So when player touches the coin object in World Space, I need to animate by moving that coin object to Coin meter, when the render mode of Canvas is Screen Space - Overlay , I can get the sprite object position easily with below code

CoinSprite 代码

GameObject coinCanvasObject = Instantiate(prefab, canvas.transform);//Instantiate coin inside Canvas view
coinCanvasObject.transform.position = Camera.main.WorldToScreenPoint(coinSpriteObject.transform.position);//getting coin position from World Space and convert to Screen Space and set to coinCanvasobject position 
AnimateCoin animate = coinCanvasObject.GetComponent<AnimateCoin>();
animate.animateCoin(coinSpriteObject.transform.position);
coinSpriteObject.SetActive(false);

动画币

public class AnimateCoin : MonoBehaviour
{
    private float speed = 0f;
    private bool isSpawn = false;
    private Vector3 screenPos;

    public void animateCoin(Vector3 screenPosTemp, Camera cam, Canvas canvas)
    {
        screenPos = Camera.main.WorldToScreenPoint(screenPosTemp);
        isSpawn = true;
    }

    private void Update()
    {
        if (isSpawn)
        {
            speed += 0.025f;
            transform.position = Vector3.Lerp(screenPos, targetObject.transform.position, speed);
            if (Vector3.Distance(transform.position, targetObject.transform.position) <= 0)
            {
                StartCoroutine(deActivateCoin());
            }
        }
    }

    private IEnumerator deActivateCoin()
    {
        isSpawn = false;
        yield return new WaitForSeconds(0.2f);
        gameObject.SetActive(false);
    }    
}

由于我需要将粒子效果带入 Canvas 视图,因此我将 Canvas 渲染模式更改为Screen Space - Camera 当我将 Canvas 更改为此渲染模式时,我无法获得确切的精灵 object position 来跟踪硬币效果。

希望这可以帮助:

public Camera           cam;    // Camera containing the canvas
public Transform        target; // object in the 3D World
public RectTransform    icon;   // icon to place in the canvas
public Canvas           canvas; // canvas with "Render mode: Screen Space - Camera"

void Update()
{
    Vector3 screenPos = cam.WorldToScreenPoint(target.position);
    float h = Screen.height;
    float w = Screen.width;
    float x = screenPos.x - (w / 2);
    float y = screenPos.y - (h / 2);
    float s = canvas.scaleFactor;
    icon.anchoredPosition = new Vector2(x, y) / s;
}

PD:它在 2D 视频游戏中非常适合我,我没有在 3D 游戏中测试它,但我认为它应该也可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM