05 Unity3D水平运动控制--《程序员学Unity3d》

前面模拟了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); 

}

 }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值