模拟物体加减速

文章介绍了在Unity中使用Acceleration脚本来模拟物体加速度,包括从0加速到最大速度、在接近目标点时减速到0的过程,并提及了在实际交通场景中需要考虑的额外因素如路口减速、转弯等。
摘要由CSDN通过智能技术生成

模拟物体加速度要考虑下面几个问题:
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就要开始提速。所以要根据具体需求再进行拓展。

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值