Unity3D控制脚本之位置(position)、旋转(rotation)、大小(scale)的实现
发表于2018-11-19
Unity也是借助了一些基础功能才组成了强大的unity引擎,本篇中要给大家介绍的是这些基础控制的脚本,包括位置(position)、旋转(rotation)、大小(scale)等,看看是如何借助这些脚本实现物体的基础控制的。
1、位置(Position):
控制位置很简单,首先要知道要在xyz哪几个轴上移动,确定好后定义代表着那些轴的移动变量,速度(m_speed在函数外定义为全局变量)然后通过if语句实现特定键对偏移量的增减,最后通过transform.translate实现移动 这些脚本要放在Update里
//在x和z轴的移动量 float movez = 0; float movex = 0; //实现移动控制 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, 0, movez));
2、旋转(Rotation):
float speed = 100.0f; float x; float z; void Update () { if(Input.GetMouseButton(0)){//鼠标按着左键移动 y = Input.GetAxis("Mouse X") * Time.deltaTime * speed; x = Input.GetAxis("Mouse Y") * Time.deltaTime * speed; }else{ x = y = 0 ; } //旋转角度(增加) transform.Rotate(new Vector3(x,y,0)); /**---------------其它旋转方式----------------**/ //transform.Rotate(Vector3.up *Time.deltaTime * speed);//绕Y轴 旋转 //用于平滑旋转至自定义目标 pinghuaxuanzhuan(); } //平滑旋转至自定义角度 void OnGUI(){ if(GUI.Button(Rect(Screen.width - 110,10,100,50),"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); } }
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, 0, z); /**---------------重新设置角度(一步到位)----------------**/ //transform.localScale = new Vector3(x, 0, z); }
如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引