我想瞄准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);
有什么主意吗?
答案 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轴(如图所示)
希望对您有帮助
答案 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;
}