如何在Unity 2D项目中查看(瞄准)预制件

时间:2018-08-30 20:40:27

标签: unity3d

我想瞄准2d预制件(它们随机生成)。我想瞄准离我的物体最近的预制件。

这不起作用:

 Vector2 direction = target.position - transform.position;
 float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
 Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
 transform.rotation = Quaternion.Slerp(transform.rotation, rotation, 
                                       speed * Time.deltaTime);

有什么主意吗?

this is full code

Here is what i want

2 个答案:

答案 0 :(得分:0)

我认为您可以找到最近的游戏对象并将其设置在target.position中。现在将脚本更改为此:

void Update () 
{
    Vector2 direction = target.position - transform.position;
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    Quaternion newQuaternion = Quaternion.Euler(new Vector3(0, 0, angle));
    transform.rotation = Quaternion.Slerp(transform.rotation, newQuaternion, speed * Time.deltaTime);
}

请注意:当您在(0,0,0)中旋转时,想要进行预制的游戏对象必须朝右x轴(如图所示)

enter image description here

希望对您有帮助

答案 1 :(得分:0)

这是一个应该让您入门的解决方案。
每当Instantiate目标时,将其添加到列表中。让我们将其称为allTargets(确保添加实例化的对象,而不是预制对象)。现在,您唯一要做的就是在该列表中找到最接近的target

public List<Transform> allTargets;

void Start()
{
    allTargets = new List<Transform>();
}

void Update () {
    Transform closestTarget = GetClosestTarget(allTargets);        
    Quaternion targetRotation = GetRotationTo(closestTarget);
    transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, speed * Time.deltaTime);
}

Quaternion GetRotationTo(Transform target)
{
    Vector3 dir = target.position - transform.position;
    float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    return Quaternion.AngleAxis(angle, Vector3.forward);
}

Transform GetClosestTarget(List<Transform> targets)
{              
    Transform closest = null;

    float minDistance = float.MaxValue;
    foreach (var t in targets)
    {
        float distance = Vector2.Distance(t.position, transform.position);
        if(distance < minDistance)
        {
            minDistance = distance;
            closest = t;
        }
    }
    return closest;
}