当前位置: 移动技术网 > IT编程>开发语言>c# > Unity实现人物旋转和移动效果

Unity实现人物旋转和移动效果

2020年03月09日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了unity实现人物旋转和移动的具体代码,供大家参考,具体内容如下

旋转

using system.collections;
using system.collections.generic;
using unityengine;
 
public class mouselook : monobehaviour {
 public enum rotationaxes
 {
 mousexandy = 0,
 mousex = 1,
 mousey = 2
 }
 
 public rotationaxes axes = rotationaxes.mousexandy;
 
 public float sensitivityhor = 9.0f;
 public float sensitivityvert = 9.0f;
 
 public float minvert = -45.0f;
 public float maxvert = 45.0f;
 
 private float _rotationx = 0;
 
 // use this for initialization
 void start () {
 rigidbody body = getcomponent<rigidbody> ();
 if (body != null) {
  body.freezerotation = true;
 }
 }
 
 // update is called once per frame
 void update () {
 //水平旋转就是以y轴作为旋转轴旋转,鼠标移动量为偏移量
 if (axes == rotationaxes.mousex) {
  transform.rotate (0, input.getaxis("mouse x") * sensitivityhor, 0);//通过“增加”旋转角度进行旋转(x,y,z为对应方向的增加量),一般用于无限制旋转
 } else if (axes == rotationaxes.mousey) {
  _rotationx -= input.getaxis ("mouse y") * sensitivityvert;
  _rotationx = mathf.clamp (_rotationx, minvert, maxvert);//限制_rotationx的值在minvert与minvert之间
  float rotationy = transform.localeulerangles.y;
  //debug.log ("rotationx:"+_rotationx+","+input.getaxis ("mouse y") * sensitivityvert);
  transform.localeulerangles = new vector3(_rotationx, rotationy, 0);//直接“设置”旋转角度进行旋转,一般用于有限制旋转
 } else {
  _rotationx -= input.getaxis ("mouse y") * sensitivityvert;
  _rotationx = mathf.clamp (_rotationx, minvert, maxvert);
  float delta = input.getaxis ("mouse x") * sensitivityhor;
  float rotationy = transform.localeulerangles.y + delta;
  transform.localeulerangles = new vector3(_rotationx, rotationy, 0);
 }
 }
}

移动

using system.collections;
using system.collections.generic;
using unityengine;
 
[requirecomponent(typeof(charactercontroller))]//如果对象没有该组件,则创建一个
[addcomponentmenu("control script/fps input")]//可以在add component查到
 
public class fpsinput : monobehaviour {
 
 private charactercontroller _charactercontroller;
 public float speed = 10.0f;
 public float gravity = -9.8f;
 // use this for initialization
 void start () {
 _charactercontroller = getcomponent<charactercontroller>();//获取对象里的某一组件
 }
 
 // update is called once per frame
 void update () {
 float deltax = input.getaxis ("horizontal") * speed;
 float deltaz = input.getaxis ("vertical") * speed;
 vector3 movement = new vector3 (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
 }
}

问题

人物移动到父容器的边缘时,人物的移动会产生偏移(甚至飞起来)。将父容器扩大,使人物无法接近边缘则不会有异常。

父容器比较大

父容器比较小,人物到达边缘

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网