Unity游戏开发的数学与物理 4:在物体运动中加入重力
发表于2017-08-30
下面是游戏开发的数学与物理运用系列里的第四篇,给大家介绍下在物体运动中加入重力。
实现注意:
- 使用级数叠加算法 y = vy
- 对位置上的加速度 vy = GR
- 速度上的加速度 GR为重力加速度,在计算机中使用的加速度单位是特殊的dot/F^2 (像素/平方帧),而不是9.8 m/s^2
(米/平方秒) - 微分是一种操作,是一种求微分系数的操作, 而微分系数是指函数关于某个值的变化率,这个概念在游戏开发中经常被用来考察某个函数变化
using UnityEngine; using System.Collections; //在物体运动中加入重力 public class ParabolicMotionTest : MonoBehaviour { //物体的X位置 float posX = 0; //物体的Y位置 float posY = 0; //物体在x方向上的速度 float speedX = 0; //物体在y方向上的速度 float speedY = -8; //屏幕的右上像素在世界空间的坐标 Vector3 ScreenRightTopPos; //屏幕的左下像素在世界空间的坐标 Vector3 ScreenLeftBottomPos; //box的半宽度 float boxHalfWidth; //运行时间 float runTime; //重力加速度 const float GR = 0.5f; //物体出生位置 Vector2 bornPos; void Start() { //将屏幕右上的像素转换为世界空间的坐标 ScreenRightTopPos = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0)); //将屏幕右下的像素转换为世界空间的坐标 ScreenLeftBottomPos = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0)); //box的半宽度,因为box是正方形 boxHalfWidth = transform.localScale.x * 0.5f; //出生位置 左上角 bornPos = new Vector2(ScreenLeftBottomPos.x boxHalfWidth, ScreenRightTopPos.y - boxHalfWidth); //初始位置屏幕左上角 transform.localPosition = new Vector3(bornPos.x, bornPos.y, 0); } void Update() { //检测,如果物体出了界面,让其重新到bornPos点 if (posX - boxHalfWidth >= ScreenRightTopPos.x || posX boxHalfWidth <= ScreenLeftBottomPos.x || posY - boxHalfWidth >= ScreenRightTopPos.y || posY boxHalfWidth <= ScreenLeftBottomPos.y) { //运行时间归0 runTime = 0f; } //x方向每帧时间内的位移到的值 posX = speedX * runTime bornPos.x; //y方向每帧时间内的位移到的值 posY = (0.5f * GR * runTime * runTime) (speedY * runTime) bornPos.y; //设置该帧的位置 transform.localPosition = new Vector3(posX, posY, 0); //时间的改变值 runTime = Time.deltaTime; } }
如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引