Unity3D实现第一人称移动,随鼠标转动视角+上楼梯(C#)
第一人称移动:
1、在层级面板创建一个Capsule,命名为Player,将层级面板中的相机拖到Player下方
2、重置Player和摄像机的Transform数值(方便调整摄像机在Player上的位置),然后调整摄像机在Player上的位置
大概将摄像机放到Player眼睛的位置即可。
3、创建一个脚本,命名为CameraControl。并挂载到摄像机上。
代码内容
public class CameraControl : MonoBehaviour
{
public Transform player;//获取玩家
private float mouseX,mouseY;//获取鼠标位置
public float mouseSensitivity;//鼠标灵敏度
private float xRotation;
private void Update()
{
mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;//在上下移动视角后,防止Y的值反弹回0(若不加这一条,每次上下移动视角移动一下后,视角都会弹回原位置,不会固定)
xRotation = Mathf.Clamp(xRotation, -70f, 70f);//摄像机上下视角限制,对于Player(主角)来说,视角上下是有限制的,不然会很诡异
player.Rotate(Vector3.up*mouseX);//玩家随鼠标旋转
transform.localRotation=Quaternion.Euler(xRotation,0,0);//摄像机旋转
}
}
4、将层级的Player拖到脚本中。
效果:(图中红线是后面操作实现的,现在没有是正确的)
5、对Player,删掉默认的Colider,添加Character Controller和Rigidbody
6、调整ChararcterController中参数来让碰撞体将Player包住(主要调整半径和高度)
7、创建一个脚本,命名为PlayerMove,挂载到Player上。
我写的是除了前后左右移动,当按下空格键,会加速
public class PlayerMove : MonoBehaviour
{
// Start is called before the first frame update
private float walk;
private float run;
private float speed;
private Vector3 dir;
private CharacterController playerController;
void Start()
{
walk = 250.0f;
run = 500.0f;
playerController = GetComponent<CharacterController>();
}
void Update()
{
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
if (Input.GetKey(KeyCode.Space))
speed = run;
else
speed = walk;
dir = transform.forward * vertical + transform.right * horizontal;
playerController.Move(dir*speed*Time.deltaTime);
}
}
上楼梯(利用射线检测)
8、在PlayerMove中添加代码,完整代码为文章来源:https://www.toymoban.com/news/detail-539105.html
public class PlayerMove : MonoBehaviour
{
private float walk;
private float run;
private float speed;
private Vector3 dir;
private Vector3 dirY;
private CharacterController playerController;
private Vector3 rayOrigin;
private Ray ray;
void Start()
{
walk = 250.0f;
run = 500.0f;
playerController = GetComponent<CharacterController>();
}
void Update()
{
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
if (Input.GetKey(KeyCode.Space))
speed = run;
else
speed = walk;
dir = transform.forward * vertical + transform.right * horizontal;
playerController.Move(dir*speed*Time.deltaTime);
rayOrigin = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z) +
this.transform.forward * speed;
ray.origin = rayOrigin;
ray.direction = new Vector3(0, -1, 0);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.DrawLine(ray.origin,hit.point,Color.red);
}
dirY.y = -this.transform.position.y+ hit.point.y;
playerController.Move(dirY);
}
9、一定要将每个台阶加上碰撞体
最终运行效果:
文章来源地址https://www.toymoban.com/news/detail-539105.html
到了这里,关于Unity3D实现第一人称移动,随鼠标转动视角+上楼梯(C#)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!