unity3D控制第一视角移动

文章目录

一、摄像机的碰撞箱

在摄像机内新建一个Capsule来判断摄像机的碰撞箱

二、开发步骤

1.Character Controller组件

添加Character Controller组件: 

2.角色移动

新建C#脚本,代码如下(使用WASD控制移动),写完后托给摄像机。

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
        float _horizontal = Input.GetAxis("Horizontal");
        float _vertical = Input.GetAxis("Vertical");
    }
    void Update()
    {
        CharacterController controller = GetComponent<CharacterController>();
        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);
    }

}

 3.视觉转动

再建一个C#脚本,代码如下,写完后托给摄像机。

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 6f;
    [SerializeField] private float jumpForce = 10;
    [SerializeField] private float gravity = 15f;

    private Vector3 moveDirection;

    [Header("Camera details")]
    public float sensetivity = 1f;
    private Transform playerCamera;
    private CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
        playerCamera = GetComponentInChildren<Camera>().transform;

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {
        transform.Rotate(0, Input.GetAxis("Mouse X") * sensetivity, 0);
        playerCamera.Rotate(-Input.GetAxis("Mouse Y") * sensetivity, 0, 0);
        if (playerCamera.localRotation.eulerAngles.y != 0)
            playerCamera.Rotate(Input.GetAxis("Mouse Y") * sensetivity, 0, 0);


        moveDirection = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, moveDirection.y, Input.GetAxis("Vertical") * moveSpeed);
        moveDirection = transform.TransformDirection(moveDirection);

        if (controller.isGrounded)
        {
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpForce;
            else
                moveDirection.y = 0;
        }

        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}

总结

希望以上内容可以对你有所帮助。