1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Unity使用键盘wasd控制绑定角色和第一人称摄像机随鼠标移动

Unity使用键盘wasd控制绑定角色和第一人称摄像机随鼠标移动

时间:2022-10-28 08:42:58

相关推荐

Unity使用键盘wasd控制绑定角色和第一人称摄像机随鼠标移动

首先创建一个物体,然后里面加上摄像机并且调整到相应的位置

在创建的物体上添加一个组件character controller

键盘控制移动代码

public float speed = 6.0F;public float jumpSpeed = 8.0F;public float gravity = 20.0F;private Vector3 moveDirection = Vector3.zero;CharacterController controller;void Start(){controller = GetComponent<CharacterController>();}void Update(){if (controller.isGrounded){moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));moveDirection = transform.TransformDirection(moveDirection);moveDirection *= speed;if (Input.GetButton("Jump"))moveDirection.y = jumpSpeed;}moveDirection.y -= gravity * Time.deltaTime;controller.Move(moveDirection * Time.deltaTime);}

摄像机跟随鼠标移动代码

public enum RotationAxes{MouseXAndY = 0,MouseX = 1,MouseY = 2}public RotationAxes axes = RotationAxes.MouseXAndY;public float sensitivityHor = 9f;public float sensitivityVert = 9f;public float minmumVert = -45f;public float maxmumVert = 45f;private float _rotationX = 0;// Use this for initializationvoid Start(){}// Update is called once per framevoid Update(){if (axes == RotationAxes.MouseX){transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);}else if (axes == RotationAxes.MouseY){_rotationX = _rotationX - Input.GetAxis("Mouse Y") * sensitivityVert;_rotationX = Mathf.Clamp(_rotationX, minmumVert, maxmumVert);float rotationY = transform.localEulerAngles.y;transform.localEulerAngles = new Vector3(-_rotationX, rotationY, 0);}else{_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;_rotationX = Mathf.Clamp(_rotationX, minmumVert, maxmumVert);float delta = Input.GetAxis("Mouse X") * sensitivityHor;float rotationY = transform.localEulerAngles.y + delta;transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);}}

然后接下来是监听键盘脚本和第一人称鼠标移动效果,全部绑定在创建的物体上

这样就可以使用键盘和鼠标模拟第一人称视角移动的效果

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。