前面模拟了Unity3d的“碰撞”,这次将通过脚本来控制物体的运动。简单使用“W”“S”“A”“D”按键来控制物体“前进”“后退”“向左转”“向右转”。
因为之前这个练习的项目文件已经不见了,暂时提供不了图片,需要的话后期补上。
----------------------
概念:使用脚本获取组件控制权
新增个正方体,绑上一个C#脚本
代码如下:
Transform tCube; //声明一个Transform(变换)类型的变量
void Start () {
//获取对应类型的组件控制权(其他组件方法类似)
tCube=(Transform)gameObject.GetComponent("Transform");
}
void Update () {
tCube.Rotate(0,15,5);
}
-----------------------
(界面UI控件使用方法)
创建一个GUIText控件,附上一个C#脚本,代码如下
GUIText txt1;
txt1=(GUIText)gameObject.GetComponent("GUIText");
static bool anyKey; //接收是否敲击了键盘
static Vector3 mousePosition; //接收鼠标坐标
anyKey=Input.anyKey; //判断是否发生key动作
anyKey=Input.GetKey(KeyCode.A); //判断是否按下了'a'
txt1.text=anyKey.ToString();
anyKey=Input.GetKey(KeyCode.A); //若松开A,为False
Input.GetKeyDown(KeyCode.A); //松口A,在按下不是A键之前仍为A
mousePosition=Input.mousePosition; // mousePosition.x为X坐标值
txt1.text=mousePosition.ToString();
bool i=Input.GetMouseButton(1); //1,2,3分别表左中右键。
//卡丁车// Terrain创建地表。创建一个正方体,加上刚体属性。
//Translate(1*Time.deltaTime,0,0,Space.Self); // Space.Self 自身坐标系。World世界坐标系。1*Time.deltaTime 一秒钟移动一个单位(控制速度)
//相机调节好视觉后,可以作为车的子类。镜头将随车而动。
public class car : MonoBehaviour {
Transform tCar;
// Use this for initialization
void Start () {
tCar=(Transform)gameObject.GetComponent("Transform");
}
// Update is called once per frame
void Update () {
//前进
if(Input.GetKey(KeyCode.W))
{
tCar.Translate(1*Time.deltaTime,0,0,Space.Self);
}
//后退
if(Input.GetKey(KeyCode.S))
{
tCar.Translate(-1*Time.deltaTime,0,0,Space.Self);
}
//左转
if(Input.GetKey(KeyCode.A))
{
tCar.Rotate(0,-15*Time.deltaTime,0,Space.Self);
}
//右转
if(Input.GetKey(KeyCode.D))
{
tCar.Rotate(0,15*Time.deltaTime,0,Space.Self);
}
}
}