物体移动
- translate(X,Y,Z)移动
void Update () {
float x=Input.GetAxis("Horizontal") * Time.deltaTime * speed;
float z= Input.GetAxis("Vertical") * Time.deltaTime * speed;
transform.Translate(x, 0,z);
}
- 刚体加力移动
//按下鼠标左键
if (Input.GetButtonDown("Fire1"))
{
//新建预制物体,预制对象,位置,旋转速度
Transform tf=Instantiate(newtf, transform.position, transform.rotation);
//刚体加力
tf.GetComponent<Rigidbody>().AddForce(transform.TransformDirection(Vector3.forward)*force);
}
- 设置刚体速度
gameObject.GetComponent<Rigidbody>().velocity=new Vector3(0,y,0);
物体旋转
//检测键盘输入
if (Input.GetKey(KeyCode.Q))
{
//物体旋转
//左右旋转,即以y轴旋转;
//Space.Self以自身坐标轴旋转,Space.World以世界坐标轴旋转
transform.Rotate(0, -1*rotateSpeed * Time.deltaTime, 0, Space.Self);
}
if(Input.GetKey(KeyCode.E))
{
transform.Rotate(0, rotateSpeed*Time.deltaTime, 0, Space.Self);
}
查找物体
//fps为name,text为类型
//fps显示方式是欠妥的
GameObject.Find("fps").GetComponent<Text>().text =
"FPS " + (1 / Time.deltaTime).ToString().Substring(0,2);
//寻找脚本组件
GameObject.FindGameObjectWithTag("MainCamera")
.GetComponent<ClassName>().enabled = false;
绘制按钮
private void OnGUI(){
if (GUI.Button(new Rect((float)(Screen.width*0.3),
(float)(Screen.width*0.1),
(float)(Screen.width*0.4),
(float)(Screen.width*0.05)),
"退出")){
//退出程序
Application.Quit();
}
if (GUI.Button(new Rect((float)(Screen.width*0.3),
(float)(Screen.width*0.2),
(float)(Screen.width*0.4),
(float)(Screen.width*0.05)),
"重新开始")){
//加载场景
SceneManager.LoadScene("1");
}
}