資源簡介
用C#寫的,能夠實現類似拋物線運動的腳本,能夠廣泛的應用于許多體育類應用場景。
public float rotateX = 45; // 箭的最大X軸旋轉角度
public float speed = 10; // 箭的速度
public float height = 10; // 箭的最大高度
代碼片段和文件信息
using?System.Collections;
using?System.Collections.Generic;
using?UnityEngine;
public?class?Trajectory?:?MonoBehaviour
{
????//?Use?this?for?initialization??
????void?Start()
????{
????????//?開始測試??
????????Vector3?end?=?transform.position;
????????end.x?=?end.x?*?-1;
????????Fire(transform.position?end);
????}
????//?Update?is?called?once?per?fram??
????void?Update()
????{
????????if?(_isFiring)
????????{
????????????UpdateArrow();
????????}
????}
????//?所有變量??
????public?float?rotateX?=?45;??????//?箭的最大X軸旋轉角度??
????public?float?speed?=?10;????????//?箭的速度??
????public?float?height?=?10;???????//?箭的最大高度???
????private?Vector3?_startPos?_stopPos?_curPos;????//?起始位置,目標位置,當前位置??
????private?float?_angleToStop;?????//?從起始點到目標點的角度??
????private?float?_startHeight?_stopHeight;?//?起始高度,結束高度??
????private?bool?_isFiring?=?false;?????//判斷箭是否正在移動??
????private?float?_totalDistance?_curDistance;??//?總距離,?當前距離??
????private?Vector3?_curRotation;?//?當前的旋轉角度??
????//?發射函數,你只要調用這一個函數就能發射箭了??
????public?void?Fire(Vector3?start?Vector3?stop)
????{
????????_startPos?=?start;
????????_stopPos?=?stop;
????????_angleToStop?=?GetAngleToStop(start?stop);?//?計算?起始位置?到?目標位置的角度??
????????_startHeight?=?start.y;
????????_stopHeight?=?stop.y;
????????_curDistance?=?0;
????????//?計算總距離??
????????Vector3?v?=?_stopPos?-?_startPos;
????????_totalDistance?=?Mathf.Sqrt(v.x?*?v.x?+?v.z?*?v.z);
????????//?設置當前位置??
????????transform.position?=?start;
????????_curPos?=?start;
????????//?設置當前X,Y軸的旋轉角度??
????????Vector3?rotation?=?transform.eulerAngles;
????????if?(rotateX?>?0)
????????{
????????????rotation.x?=?-rotateX;
????????}
????????rotation.y?=?_angleToStop;
????????transform.eulerAngles?=?rotation;
????????_curRotation?=?rotation;
????????//?設置判斷爲發射狀態,讓Update函數能夠更新??
????????_isFiring?=?true;
????}
????//?計算?起始位置?到?目標位置的角度??
????private?float?GetAngleToStop(Vector3?startPos?Vector3?stopPos)
????{
????????stopPos.x?-=?startPos.x;
????????stopPos.z?-=?startPos.z;
????????float?deltaAngle?=?0;
????????if?(stopPos.x?==?0?&&?stopPos.z?==?0)
????????{
????????????return?0;
????????}
????????else?if?(stopPos.x?>?0?&&?stopPos.z?>?0)
????????{
????????????deltaAngle?=?0;
????????}
????????else?if?(stopPos.x?>?0?&&?stopPos.z?==?
評論
共有 條評論