Files
valheim/Assets/_Valheim/Scripts/Move2Point.cs
2025-07-04 14:16:14 +08:00

47 lines
1.3 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valheim;
public class Move2Point : MonoBehaviour
{
public Rigidbody rb;
public Vector3 targetPoint;
public float speed = 10f;
[NonSerialized]
public Action cb;
private bool finished = false;
void Start()
{
// 确保刚体被赋值
if (rb == null) rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (cb != null && !finished)
{
// 计算移动方向
Vector3 direction = targetPoint - rb.position;
// 设置刚体的速度
rb.velocity = direction.normalized * speed;
// 让游戏对象面向移动方向
Quaternion toRotation = Quaternion.LookRotation(direction);
rb.rotation = Quaternion.Lerp(rb.rotation, toRotation, Time.fixedDeltaTime * 20F);
// 如果当前位置足够接近目标点,则停止移动
if (Vector3.Distance(rb.position, targetPoint) < 0.1f)
{
finished = true;
rb.velocity = Vector3.zero;
// 如果需要,可以在这里加上停止移动的逻辑
cb.Invoke();
}
}
}
}