简体   繁体   English

Unity Health Bar在敌人头上

[英]Unity Health Bar over Enemy Head

I'm having some problems with this so i thought i'd ask here. 我对此有一些问题,所以我想在这里问。

I wrote a code that instantiates a health bar (a simple slider) and an enemy. 我编写了一个实例化一个健康栏(一个简单的滑块)和一个敌人的代码。 It then sets that enemy (who just spawned) as the target of that health bar and the healthbar updates its position to always stay above the enemys head. 然后,它将该敌人(刚刚生成的)设置为该生命条的目标,并且该生命条会更新其位置以始终保持在敌人头上方。

This is the script for the health bar (canvasRect is the rect transform of the canvas, myRect is the health bars rect transform): 这是运行状况栏的脚本(canvasRect是画布的rect转换,myRect是运行状况栏的rect转换):

private void Update() {
        if(target != null) {
            Vector2 targetPosition = Camera.main.WorldToViewportPoint(target.position);

            Vector2 screenPosition = new Vector2(((targetPosition.x * canvasRect.sizeDelta.x) - (canvasRect.sizeDelta.x * 0.5f)),
                ((targetPosition.y * canvasRect.sizeDelta.y) - (canvasRect.sizeDelta.y * 0.5f)));

            screenPosition += new Vector2(0f, 15f);

            myRect.anchoredPosition = screenPosition;
        }
    }

The script works great, but there is one problem: as you can see, i'm adding an offset in the y coordinate. 该脚本很好用,但是有一个问题:如您所见,我在y坐标中添加了一个偏移量。 This is to place the health bar above the enemy, not inside of it. 这是将生命条放置在敌人之上 ,而不是内部

The problem comes when i move the camera however. 问题出在我移动相机时。 If i zoom in, it rotates a bit (like an RTS camera) which means that the offset is wrong. 如果我放大,它会旋转一点(就像RTS相机一样),这意味着偏移是错误的。 The further i zoom in, the lower the health bar goes (as the offset of 15f is not enough anymore). 我放大得越远,运行状况条越低(因为15f的偏移量不再足够)。 And then when i move the camera closer to the enemy, it again pushes the health bar into him. 然后,当我将相机移近敌人时,它再次将健康栏推入敌人体内。

Is there a way to get the "border" of my enemy in screensize so i can always know what offset to have? 有没有办法让我的敌人获得“屏幕尺寸”的“边界”,这样我就始终可以知道要获得的偏移量是多少? Or is there another solution? 还是有其他解决方案?

Thanks in advance! 提前致谢!

The solution is simple. 解决方案很简单。 Don't add the offset to the screen position. 不要将偏移量添加到屏幕位置。 Instead, add it to the enemy world position (target.position + offset). 而是将其添加到敌人的世界位置(target.position +偏移量)。

In addition to that you can get the bounds of the mesh by using MeshRenderer.bounds. 除此之外,您还可以使用MeshRenderer.bounds获得网格的边界。

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

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