如上图所示,我有两个GameObject
:汽车和圆圈。汽车跟随圆圈,圆圈随光标移动。目前,我的汽车正在远处追随圆。当圆沿x轴移动时,我想像漂移一样旋转汽车。
这是我的汽车追踪脚本:
public class Follow : MonoBehaviour
{
public Transform leader;
public float followSharpness = 0.1f;
Vector3 _followOffset;
void Start()
{
// Cache the initial offset at time of load/spawn:
_followOffset = transform.position - leader.position;
}
void LateUpdate()
{
// Apply that offset to get a target position.
Vector3 targetPosition = leader.position + _followOffset;
//GetComponent<Rigidbody2D>().rotation = 1.5f;
// Keep our y position unchanged.
//targetPosition.y = transform.position.y;
// Smooth follow.
transform.position += (targetPosition - transform.position) * followSharpness;
}
}
答案 0 :(得分:1)
您可以尝试使用Transform.LookAt:
void LateUpdate()
{
Vector3 targetPosition = leader.position + _followOffset;
transform.position += (targetPosition - transform.position) * followSharpness;
transform.LookAt(leader);
}
免责声明:我目前无法测试此代码是否有效,您必须对其进行尝试,看看它是否产生了预期的结果。
答案 1 :(得分:1)
因此,根据您的描述,是要让汽车始终面向光标,所以它始终“看着”光标,这是您可以执行的操作:
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 90);