斜抛运动:
1.物体以一定的初速度斜向射出去,物体所做的这类运动叫做斜抛运动。
2.斜抛运动看成是作水平方向的匀速直线运动和竖直方向的竖直上抛运动的合运动。
3.它的运动轨迹是抛物线。
ObliqueThrow.cs
1 using System; 2 using UnityEngine; 3 4 public class ObliqueThrow : MonoBehaviour { 5 6 private readonly float gravity = -9.8f; //重力加速度 7 private Vector2 horizontalDir; //水平方向 8 private float startSpeed; //初速度 9 private float sinValue; //sin值 10 private float cosValue; //cos值 11 private Vector3 startPos; //开始位置 12 private float endY; //结束高度(地面高度) 13 private float timer; //运动消耗时间 14 private Action<GameObject> finishCallBack; //落地后的回调 15 private bool canMove = false; //能否运动 16 17 void Update() 18 { 19 if (!canMove) 20 { 21 return; 22 } 23 24 //移动过程 25 timer = timer + Time.deltaTime; 26 27 float xOffset = startSpeed * timer * cosValue * horizontalDir.x; 28 float zOffset = startSpeed * timer * cosValue * horizontalDir.y; 29 float yOffset = startSpeed * timer * sinValue + 0.5f * gravity * timer * timer; 30 31 Vector3 endPos = startPos + new Vector3(xOffset, yOffset, zOffset); 32 if (endPos.y < endY) 33 { 34 endPos.y = endY; 35 canMove = false; 36 } 37 transform.position = endPos; 38 39 //移动结束 40 if (!canMove) 41 { 42 finishCallBack(gameObject); 43 Destroy(this); 44 } 45 } 46 47 public void StartMove(Vector2 horizontalDir, float startSpeed, float angle, float endY, Action<GameObject> finishCallBack) 48 { 49 this.horizontalDir = horizontalDir; 50 this.startSpeed = startSpeed; 51 sinValue = Mathf.Sin(Mathf.Deg2Rad * angle); 52 cosValue = Mathf.Cos(Mathf.Deg2Rad * angle); 53 startPos = transform.position; 54 this.endY = endY; 55 timer = 0; 56 this.finishCallBack = finishCallBack; 57 canMove = true; 58 } 59 }
TestThrow.cs
1 using UnityEngine; 2 using System.Collections.Generic; 3 4 public class TestThrow : MonoBehaviour { 5 6 public GameObject testGo; 7 private bool isDebug = false; 8 private List<GameObject> drawGoList = new List<GameObject>(); 9 10 void Update () 11 { 12 if (Input.GetKeyDown(KeyCode.Q)) 13 { 14 //半径为1的方向圆 15 float randomNum = Random.Range(0f, 1f);//[0, 1] 16 float x = randomNum * 2 - 1;//[-1, 1] 17 float z = Mathf.Sqrt(1 - x * x); 18 if (Random.Range(0f, 1f) > 0.5f) 19 { 20 z = -z; 21 } 22 23 isDebug = true; 24 ObliqueThrow obliqueThrow = testGo.AddComponent<ObliqueThrow>(); 25 obliqueThrow.StartMove(new Vector2(1, 0), 5f, 45f, 0f, (go) => { 26 isDebug = false; 27 Debug.Log("移动结束"); 28 }); 29 } 30 else if(Input.GetKeyDown(KeyCode.W)) 31 { 32 testGo.transform.position = new Vector3(0f, 5f, 0f); 33 for (int i = 0; i < drawGoList.Count; i++) 34 { 35 Destroy(drawGoList[i]); 36 } 37 drawGoList.Clear(); 38 } 39 40 if (isDebug) 41 { 42 GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); 43 go.transform.position = testGo.transform.position; 44 go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); 45 drawGoList.Add(go); 46 } 47 } 48 }
效果如下: