Unity 3D 中实现对物体 位置(position) 旋转(rotation) 大小(scale) 的全面控制

时间:2022-06-18 03:52:32

今天分享一些基础控制的脚本

1.位置(Position):

控制位置很简单,首先要知道要在xyz哪几个轴上移动,确定好后定义代表着那些轴的移动变量,速度(m_speed在函数外定义为全局变量)然后通过if语句实现特定键对偏移量的增减,最后通过transform.translate实现移动  这些脚本要放在Update里

         //在x和z轴的移动量
float movez = ;
float movex = ;
//实现移动控制
if (Input.GetKey(KeyCode.UpArrow)||Input.GetKey(KeyCode.W))
{
movez += m_speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
{
movez -= m_speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
movex -= m_speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
movex += m_speed * Time.deltaTime;
}
m_transform.Translate(new Vector3(movex, , movez));

2.旋转(Rotation):

 float speed = 100.0f;
float x;
float z; void Update () {
  if(Input.GetMouseButton()){//鼠标按着左键移动
    y = Input.GetAxis("Mouse X") * Time.deltaTime * speed;
    x = Input.GetAxis("Mouse Y") * Time.deltaTime * speed;
  }else{
    x = y = ;
  }
  
  //旋转角度(增加)
  transform.Rotate(new Vector3(x,y,));
  /**---------------其它旋转方式----------------**/
  //transform.Rotate(Vector3.up *Time.deltaTime * speed);//绕Y轴 旋转   //用于平滑旋转至自定义目标
  pinghuaxuanzhuan();
} //平滑旋转至自定义角度 void OnGUI(){
  if(GUI.Button(Rect(Screen.width - ,,,),"set Rotation")){
    //自定义角度     targetRotation = Quaternion.Euler(45.0f,45.0f,45.0f);
    // 直接设置旋转角度
    //transform.rotation = targetRotation;     // 平滑旋转至目标角度
    iszhuan = true;
  }
} bool iszhuan= false;
Quaternion targetRotation; void pinghuaxuanzhuan(){
  if(iszhuan){
    transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * );
  }
}

3.大小(Scale):

 float speed = 5.0f;
float x;
float z; void Update () {
x = Input.GetAxis("Horizontal") * Time.deltaTime * speed; //水平
z = Input.GetAxis("Vertical") * Time.deltaTime * speed; //垂直//"Fire1","Fine2","Fine3"映射到Ctrl,Alt,Cmd键和鼠标的三键或腰杆按钮。新的输入轴可以在Input Manager中添加。
transform.localScale += new Vector3(x, , z); /**---------------重新设置角度(一步到位)----------------**/
//transform.localScale = new Vector3(x, 0, z);
}