空间与运动
1、简答并用程序验证
- 游戏对象运动的本质是什么?
- 请用三种方法以上方法,实现物体的抛物线运动。(如,修改Transform属性,使用向量Vector3的方法…)
- 写一个程序,实现一个完整的太阳系, 其他星球围绕太阳的转速必须不一样,且不在一个法平面上。
1、游戏对象运动的本质是什么?
- 游戏对象运动的本质就是使用矩阵变换(平移、旋转、缩放)改变游戏对象的空间属性。观察游戏对象的Transform属性,可以找到Position、Rotation和Scale这三个个属性。分别是绝对或者相对位置的改变,所处位置的角度的旋转变化以及对象缩放的的变化。
请用三种方法以上方法,实现物体的抛物线运动。(如,修改Transform属性,使用向量Vector3的方法…)
第一种:修改Transform属性,水平方向上有个初速度,竖直方向上有个重力加速度。在每个时间区间内改变position属性就可以实现抛物线运动。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test1 : MonoBehaviour
{
private float xspeed = 5; //x方向的初速度
private float zspeed = 0; //z方向的初速度
private float g = 10; //重力的加速度
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
zspeed += g * Time.deltaTime;
this.transform.position += Vector3.right * Time.deltaTime * xspeed; //Sx= v0*t
this.transform.position += Vector3.down * Time.deltaTime * zspeed;
}
}
第二种:创建一个Vector3向量,同时定义该变量的值。每次把postion对该向量叠加并改变向量的y值,相当于对y方向速度不断增加。而x的值保持不变,相当于匀速。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test2 : MonoBehaviour
{
private float xspeed = 5; //x方向初的速度
private float zspeed = 0; //z方向的初速度
private float g = 10; //重力加速度
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
zspeed += g * Time.deltaTime;
Vector3 v = new Vector3(Time.deltaTime * xspeed,-Time.deltaTime * zspeed,0);
this.transform.position += v;
}
}
第三种:使用transform.Translate方法。将第二种方法中对v的叠加改为transform的Translate方法来改变position属性即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test3 : MonoBehaviour
{
// Start is called before the first frame update
private float xspeed = 5; //x方向初速度
private float zspeed = 0; //z方向初速度
private float g = 10; //重力加速度
void Start()
{
}
// Update is called once per frame
void Update()
{
zspeed += g * Time.deltaTime;
Vector3 v = new Vector3(Time.deltaTime * xspeed,-Time.deltaTime * zspeed,0);
this.transform.Translate(v);
}
}
写一个程序,实现一个完整的太阳系, 其他星球围绕太阳的转速必须不一样,且不在一个法平面上。
首先先新建好我们的八大行星,如图所示,太阳为父对象。
然后按照一定的比例调整好各个星球的大小,再将八大行星的位置排好,修改它们的transform属性即可。
- 将所有对象的行动写在一个代码里,然后添加到Sun上即可。GameObject.Find函数找到该游戏对象,而transform函数中的RotationAround跟Rotation函数分别是用来实现公转跟自转。
- RotationAround需要三个参数,第一个参数是旋转的中心,都以太阳为旋转中心;第二个参数是旋转轴,一个Vector3变量,通过改变旋转轴的属性;第三个参数是增量时间,用来改变公转的速度。
- Rotation函数可以只需要一个参数,那就是旋转时的方向及速度,用Vector3.up代表该物体是沿着自己的Y轴进行旋转,后面的参数代表旋转的角速度,由此实现自转。
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sun : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
GameObject.Find("Earth").transform.RotateAround(Vector3.zero, new Vector3(0, 1, 0), 15 * Time.deltaTime);
GameObject.Find("Earth").transform.Rotate(Vector3.up * Time.deltaTime * 100);
Ga