Unity 斜抛运动 & 路径点

1.截图

Unity 斜抛运动 & 路径点_第1张图片 Unity 斜抛运动 & 路径点_第2张图片

2.代码介绍

使用Unity自带Rigidbody刚体插件。

代码比较简单:使用Unity的 Rigidbody.velocity 进行位移(不使用AddForce)。

private Vector2 GetForce(Vector3 fromPos, Vector3 toPos){
	return (new Vector2 (toPos.x, toPos.y) - new Vector2 (fromPos.x, fromPos.y)) * power;
}
//给予一个目标点
ball.GetComponent ().velocity = GetForce(this.transform.position,Camera.main.ScreenToWorldPoint(Input.mousePosition));

抛物线计算(Trajectory)

//setTrajectoryPoints(this.transform.position, force)
void setTrajectoryPoints(Vector3 pStartPosition , Vector3 pVelocity ){
	// 求模 velocity = pVelocity.magnitude
	//float velocity = Mathf.Sqrt ((pVelocity.x * pVelocity.x) + (pVelocity.y * pVelocity.y)); 
	float velocity = pVelocity.magnitude;
	float angle = Mathf.Rad2Deg * (Mathf.Atan2 (pVelocity.y, pVelocity.x)); //获得角度

	var velocityX = velocity * Mathf.Cos (angle * Mathf.Deg2Rad); //水平方向初始速度
	var velocityY = velocity * Mathf.Sin (angle * Mathf.Deg2Rad); //垂直方向初始速度

	float fTime = 0;
	fTime += 0.1f;

	// Physics2D.gravity.magnitude = g = 9.8f;
	//计算坐标位移点
	for (int i = 0; i < numOfTrajectoryPoints; i++) {
		float dx = velocityX * fTime; //Sx = vt
		float dy = velocityY * fTime - (Physics2D.gravity.magnitude * fTime * fTime / 2.0f); //竖直上抛运动 Sy=Vot- gt*t/2
		Vector3 pos = new Vector3 (pStartPosition.x + dx, pStartPosition.y + dy, 2);
		trajectoryPoints [i].transform.position = pos;
		trajectoryPoints [i].GetComponent ().enabled = true;
		trajectoryPoints[i].transform.eulerAngles = new Vector3(0,0,Mathf.Atan2(pVelocity.y - (Physics.gravity.magnitude)*fTime,pVelocity.x)*Mathf.Rad2Deg);
		fTime += 0.1f;
	}
}

运行效果Gif:

Unity 斜抛运动 & 路径点_第3张图片

项目下载地址:

https://download.csdn.net/download/lile1234_show/10682926

你可能感兴趣的:(Unity)