unity3d物体向目标前进c#代码
时间: 2023-09-29 07:06:24 浏览: 44
#Unity3D怎么实现物体向目标前进?
要让物体向目标前进,可以将目标的位置减去物体的位置得到方向,然后将物体往该方向移动。具体实现方法有以下两种:
1.使用Transform.Translate方法
实现代码如下:
// 目标物体位置
public Transform targetTransform;
// 运动速度
public float speed = 10f;
void Update()
{
// 计算方向
Vector3 direction = targetTransform.position - transform.position;
// 根据方向进行移动
transform.Translate(direction.normalized * speed * Time.deltaTime);
}
2.使用Rigidbody组件的AddForce方法
实现代码如下:
// 目标物体位置
public Transform targetTransform;
// 运动速度
public float speed = 10f;
// 刚体组件
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
// 计算方向
Vector3 direction = targetTransform.position - transform.position;
// 根据方向施加力
rb.AddForce(direction.normalized * speed);
}
以上两种方法都可以实现物体向目标前进的效果,具体可以根据自己的需求选择实现方式。