游戏Unity编程

问题描述 投票:0回答:1

我正在制作一个根据玩家的位置和旋转指向敌人位置的箭头,但我的代码不能很好地工作。

Vector3 FirstPoint = (Player.position - transform.position).normalized; // Direção inicial do objeto
        Vector3 LastPoint = (Inimigo.position - transform.position).normalized; // Direção final do objeto

        float angle = Vector3.Angle(FirstPoint, LastPoint);

        Quaternion PlayerRotation = Player.rotation;
        float KartYrotation = Player.eulerAngles.y;
        if (KartYrotation > 180f)
        {
            KartYrotation -= 360f;
        }
        Quaternion rightrotation = Quaternion.Euler(0f, 0f, angle - KartYrotation);

        transform.rotation = rightrotation;  

我希望箭头指向敌人。

c# unity-game-engine
1个回答
0
投票

有很多方法可以做到这一点,但这里有一个相当简单的方法:

  1. 在编辑器中创建一个空的游戏对象(下图中称为“箭头”),并将箭头的表示作为其子对象。在我的示例中,我使用圆柱体作为表示。

  2. 在编辑器中,调整箭头表示的方向,以便如果敌人站在箭头的正前方,它就会指向正确的方向:

Arrow game object with a cylinder child pointed forward.

  1. 向玩家对象添加一个脚本,使箭头成为玩家的子对象,然后更新其方向以查看敌人:
public class PointArrowAtEnemy : MonoBehaviour
{
    public GameObject arrow;
    public Transform enemy;

    void Start()
    {
        // First, set the arrow as our child
        arrow.transform.SetParent(transform);
    }

    void Update()
    {
        // Center the arrow relative to our position
        arrow.transform.localPosition = Vector3.zero;

        // Have the arrow look at the enemy position
        arrow.transform.LookAt(enemy);
    }
}

您也可以通过其他方式执行此操作,具体取决于您的游戏设置。

© www.soinside.com 2019 - 2024. All rights reserved.