热点
如果您想在通用对象上的特定位置放置可以在任何地方缩放或转换的东西,那么“热点”可能特别有用。
什么是热点?
编辑目标游戏对象(本例中的行)并向其添加一个空游戏对象。给它一个合适的名称——例如“交叉武器热点”,然后将其移动到您希望其他游戏对象定位的位置。本质上,热点只是一个空的游戏对象 - 一种放置标记。
如何使用它?
您所需要的只是对热点游戏对象的引用。您可以通过向为您跟踪它的极点游戏对象添加一个小脚本来做到这一点:
public class PowerPole : MonoBehaviour {
public GameObject CrossArmsHotspot; // Set this in the inspector
}
然后您可以从任何电线杆实例中获取该热点参考,如下所示:
var targetHotspot = aPowerPoleGameObject.GetComponent<PowerPole>().CrossArmsHotspot;
那么这只是让您的目标对象使用您喜欢的任何技术将自己放置在该热点所在的位置的情况。如果你想让它“粘”在那里,那么:
void Start(){
targetHotspot = aPowerPoleGameObject.GetComponent<PowerPole>().CrossArmsHotspot;
}
void Update(){
transform.position = targetHotspot.transform.position;
}
将是一个(简化的)示例。
使用 lerp 向热点移动的更高级示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CrossArmsMover : MonoBehaviour
{
public GameObject PowerPole;
private GameObject targetHotspot;
public GameObject CrossArms;
public float TimeToTake = 5f;
private float timeSoFar;
private Vector3 startPosition;
private Quaternion startRotation;
// Start is called before the first frame update
void Start()
{
startPosition = CrossArms.transform.position;
startRotation = CrossArms.transform.rotation;
targetHotspot = PowerPole.GetComponent<PowerPole>().CrossArmsHotspot;
}
// Update is called once per frame
void Update()
{
timeSoFar+=Time.deltaTime;
var progress = timeSoFar/TimeToTake;
// Clamp it so it doesn't go above 1.
if(progress > 1f){
progress = 1f;
}
// Target position / rotation is..
var targetPosition = targetHotspot.transform.position;
var targetRotation = targetHotspot.transform.rotation;
// Lerp towards that target transform:
CrossArms.transform.position = Vector3.Lerp(startPosition, targetPosition, progress);
CrossArms.transform.rotation = Quaternion.Lerp(startRotation, targetRotation, progress);
}
}