[脚本] 转载一个抛物线的代码

本文介绍了一个使用Unity实现物体抛物线运动的简单方法。通过计算物体的初始速度、施加力的方向与大小,使物体能精确地从起点移动到指定的目标位置。此方案考虑了重力加速度的影响,并在每帧更新中施加必要的力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. using UnityEngine;
  2. using System.Collections;
  3. public class test : MonoBehaviour {
  4.     public float m = 2, g = 9.81f, tUp = 0.5f;//m:质量 g:重力 tup:希望到达最高点的时间
  5.     private float forceUp, forceRight, vUp0, highest, tUpTotal, vRight;//forceup: 垂直方向的力 vup0:垂直初速度  highest: 最高点 tUpTotal: 总时间
  6.     public Transform target;//目标位置物体
  7.     public bool isParabola;
  8.     // Use this for initialization
  9.     void Start()
  10.     {
  11.         vUp0 = g * tUp;//求出锤子的初速度
  12.         forceUp = g + vUp0 * m / Time.fixedDeltaTime;//垂直方向添加的力
  13.         highest = transform.position.y + 0.5f * g * tUp * tUp;//计算最高点的高度
  14.         tUpTotal = Mathf.Sqrt(Mathf.Abs(target.position.y - highest) * 2 / g) + tUp;//总时间计算
  15.         vRight = (target.position.x - transform.position.x) / tUpTotal;//求出水平速度
  16.         forceRight = vRight / Time.fixedDeltaTime * m;//水平方向添加的力
  17.     }
  18.     void FixedUpdate()
  19.     {
  20.         if (isParabola)
  21.         {
  22.             isParabola = false;
  23.             rigidbody.AddForce(Vector3.up * forceUp);
  24.             rigidbody.AddForce(Vector3.right * forceRight);
  25.         }
  26.     }
  27.     void OnGUI()
  28.     {
  29.         if (GUILayout.Button("dsfsd"))
  30.         {
  31.             isParabola = true;
  32.         }
  33.     }
  34. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值