模拟物体加速度要考虑下面几个问题:
1、距离目标点距离够长的情况下速度从0到最大速度
2、距离目标点距离比较短的情况下速度达不到最大速度就开始减速
3、如果当前速度大于最大速度,则限制速度为最大速度
3、实时计算当前位置距离目标点的距离并实时计算当前速度
4、实时计算开始减速的距离——>S=(V²-V₀²)/(2a)
以减小到0为例:S=V²/(2a)
以下为具体步骤:
新建场景,创建一个cube和两个位置点
编辑Acceleration脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Acceleration : MonoBehaviour
{
public Transform pointA; // 起点
public Transform pointB; // 终点
public float acceleration = 1f; // 加速度
public float maxSpeed = 5f; // 最大速度
public float minDistanceToStartDeceleration = 2f; // 最小距离开始减速
private Rigidbody rb;
private Vector3 targetPosition;
public float currentSpeed = 0f;
void Start()
{
rb = GetComponent<Rigidbody>();
// 将目标位置设置为终点位置
targetPosition = pointB.position;
}
void FixedUpdate()
{
// 计算当前位置到目标位置的向量
Vector3 direction = targetPosition - transform.position;
// 计算距离目标点的距离
float distanceToTarget = direction.magnitude;
// 计算当前速度
currentSpeed += acceleration * Time.fixedDeltaTime;
// 如果当前速度大于最大速度,将当前速度限制为最大速度
currentSpeed = Mathf.Min(currentSpeed, maxSpeed);
// 计算开始减速的距离
float decelerationDistance = (currentSpeed * currentSpeed) / (2 * acceleration);
// 如果距离小于开始减速的距离,逐渐减小速度
if (distanceToTarget <= decelerationDistance + minDistanceToStartDeceleration)
{
float t = Mathf.Clamp01((distanceToTarget - minDistanceToStartDeceleration) / decelerationDistance);
currentSpeed = Mathf.Lerp(0f, maxSpeed, t);
}
// 使用刚体施加力来模拟加速度
rb.velocity = direction.normalized * currentSpeed;
// 如果物体接近目标位置,切换目标位置为起始点
if (distanceToTarget < 0.1f)
{
targetPosition = (targetPosition == pointA.position) ? pointB.position : pointA.position;
currentSpeed = 0f; // 重置速度
}
}
}
物体上挂载Acceleration脚本,添加位置点和加速度。
以下为实现效果预览
实际运用过程中,要考虑很多因素,以交通汽车为例:
遇到路口减速、转弯、遇到红路灯以及避让。并不会减速到0就要开始提速。所以要根据具体需求再进行拓展。