Unity实现人物旋转和移动效果
本文实例为大家分享了Unity实现人物旋转和移动的具体代码,供大家参考,具体内容如下
旋转
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
publicclassMouseLook:MonoBehaviour{
publicenumRotationAxes
{
MouseXandY=0,
MouseX=1,
MouseY=2
}
publicRotationAxesaxes=RotationAxes.MouseXandY;
publicfloatsensitivityHor=9.0f;
publicfloatsensitivityVert=9.0f;
publicfloatminVert=-45.0f;
publicfloatmaxVert=45.0f;
privatefloat_rotationX=0;
//Usethisforinitialization
voidStart(){
Rigidbodybody=GetComponent();
if(body!=null){
body.freezeRotation=true;
}
}
//Updateiscalledonceperframe
voidUpdate(){
//水平旋转就是以Y轴作为旋转轴旋转,鼠标移动量为偏移量
if(axes==RotationAxes.MouseX){
transform.Rotate(0,Input.GetAxis("MouseX")*sensitivityHor,0);//通过“增加”旋转角度进行旋转(X,Y,Z为对应方向的增加量),一般用于无限制旋转
}elseif(axes==RotationAxes.MouseY){
_rotationX-=Input.GetAxis("MouseY")*sensitivityVert;
_rotationX=Mathf.Clamp(_rotationX,minVert,maxVert);//限制_rotationX的值在minVert与minVert之间
floatrotationY=transform.localEulerAngles.y;
//Debug.Log("rotationX:"+_rotationX+","+Input.GetAxis("MouseY")*sensitivityVert);
transform.localEulerAngles=newVector3(_rotationX,rotationY,0);//直接“设置”旋转角度进行旋转,一般用于有限制旋转
}else{
_rotationX-=Input.GetAxis("MouseY")*sensitivityVert;
_rotationX=Mathf.Clamp(_rotationX,minVert,maxVert);
floatdelta=Input.GetAxis("MouseX")*sensitivityHor;
floatrotationY=transform.localEulerAngles.y+delta;
transform.localEulerAngles=newVector3(_rotationX,rotationY,0);
}
}
}
移动
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
[RequireComponent(typeof(CharacterController))]//如果对象没有该组件,则创建一个
[AddComponentMenu("ControlScript/FPSInput")]//可以在AddComponent查到
publicclassFPSInput:MonoBehaviour{
privateCharacterController_characterController;
publicfloatspeed=10.0f;
publicfloatgravity=-9.8f;
//Usethisforinitialization
voidStart(){
_characterController=GetComponent();//获取对象里的某一组件
}
//Updateiscalledonceperframe
voidUpdate(){
floatdeltaX=Input.GetAxis("Horizontal")*speed;
floatdeltaZ=Input.GetAxis("Vertical")*speed;
Vector3movement=newVector3(deltaX,0,deltaZ);
movement=Vector3.ClampMagnitude(movement,speed);//保持各方向的速度相同
movement.y=gravity;
movement=movement*Time.deltaTime;//向量可以直接乘以一个数,Time.deltaTime确保在每台计算机上的速度相同
movement=transform.TransformDirection(movement);//将本地坐标转换为世界坐标
_characterController.Move(movement);//通过CharacterController进行移动而不是transform.Translate
}
}
问题
人物移动到父容器的边缘时,人物的移动会产生偏移(甚至飞起来)。将父容器扩大,使人物无法接近边缘则不会有异常。
父容器比较大
父容器比较小,人物到达边缘
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。