unity基础1

物体移动

  1. 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);
}
  1. 刚体加力移动
//按下鼠标左键
if (Input.GetButtonDown("Fire1"))
{
  //新建预制物体,预制对象,位置,旋转速度
  Transform tf=Instantiate(newtf, transform.position, transform.rotation);
  //刚体加力
  tf.GetComponent().AddForce(transform.TransformDirection(Vector3.forward)*force);
}
        
  1. 设置刚体速度
gameObject.GetComponent().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 =
   "FPS " + (1 / Time.deltaTime).ToString().Substring(0,2);

//寻找脚本组件
GameObject.FindGameObjectWithTag("MainCamera")
                .GetComponent().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");
    }
    
}

你可能感兴趣的:(unity基础1)