[Unity算法]斜抛运动

时间:2023-03-08 22:46:24

斜抛运动:

1.物体以一定的初速度斜向射出去,物体所做的这类运动叫做斜抛运动。

2.斜抛运动看成是作水平方向的匀速直线运动和竖直方向的竖直上抛运动的合运动。

[Unity算法]斜抛运动

3.它的运动轨迹是抛物线。

[Unity算法]斜抛运动

ObliqueThrow.cs

 using System;
using UnityEngine; public class ObliqueThrow : MonoBehaviour { private readonly float gravity = -9.8f; //重力加速度
private Vector2 horizontalDir; //水平方向
private float startSpeed; //初速度
private float sinValue; //sin值
private float cosValue; //cos值
private Vector3 startPos; //开始位置
private float endY; //结束高度(地面高度)
private float timer; //运动消耗时间
private Action<GameObject> finishCallBack; //落地后的回调
private bool canMove = false; //能否运动 void Update()
{
if (!canMove)
{
return;
} //移动过程
timer = timer + Time.deltaTime; float xOffset = startSpeed * timer * cosValue * horizontalDir.x;
float zOffset = startSpeed * timer * cosValue * horizontalDir.y;
float yOffset = startSpeed * timer * sinValue + 0.5f * gravity * timer * timer; Vector3 endPos = startPos + new Vector3(xOffset, yOffset, zOffset);
if (endPos.y < endY)
{
endPos.y = endY;
canMove = false;
}
transform.position = endPos; //移动结束
if (!canMove)
{
finishCallBack(gameObject);
Destroy(this);
}
} public void StartMove(Vector2 horizontalDir, float startSpeed, float angle, float endY, Action<GameObject> finishCallBack)
{
this.horizontalDir = horizontalDir;
this.startSpeed = startSpeed;
sinValue = Mathf.Sin(Mathf.Deg2Rad * angle);
cosValue = Mathf.Cos(Mathf.Deg2Rad * angle);
startPos = transform.position;
this.endY = endY;
timer = ;
this.finishCallBack = finishCallBack;
canMove = true;
}
}

TestThrow.cs

 using UnityEngine;
using System.Collections.Generic; public class TestThrow : MonoBehaviour { public GameObject testGo;
private bool isDebug = false;
private List<GameObject> drawGoList = new List<GameObject>(); void Update ()
{
if (Input.GetKeyDown(KeyCode.Q))
{
//半径为1的方向圆
float randomNum = Random.Range(0f, 1f);//[0, 1]
float x = randomNum * - ;//[-1, 1]
float z = Mathf.Sqrt( - x * x);
if (Random.Range(0f, 1f) > 0.5f)
{
z = -z;
} isDebug = true;
ObliqueThrow obliqueThrow = testGo.AddComponent<ObliqueThrow>();
obliqueThrow.StartMove(new Vector2(, ), 5f, 45f, 0f, (go) => {
isDebug = false;
Debug.Log("移动结束");
});
}
else if(Input.GetKeyDown(KeyCode.W))
{
testGo.transform.position = new Vector3(0f, 5f, 0f);
for (int i = ; i < drawGoList.Count; i++)
{
Destroy(drawGoList[i]);
}
drawGoList.Clear();
} if (isDebug)
{
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.transform.position = testGo.transform.position;
go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
drawGoList.Add(go);
}
}
}

效果如下:

[Unity算法]斜抛运动