Unity 简易第一人称角色控制器移动和视角控制

交互方式:WASD控制摄像机移动,鼠标右键控制摄像机视角旋转。

实现操作

1、unity 工程中创建胶囊体,移除Mesh Renderer组件
2、添加Rigidbody组件,按照下图设置参数
在这里插入图片描述

3、创建一个平面(使用Plane或Cube均可),调整胶囊体与摄像机位置,使摄像机位于胶囊体上方合适位置,设置胶囊体为摄像机的父物体,并设置胶囊体在平面上方的位置。
4、将 playerMove.cs脚本添加到胶囊体物体上,并将摄像机物体拖到脚本中Eye物体中,代码如下。

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using UnityEngine;
using UnityEngine.EventSystems;

public class playerMove : MonoBehaviour
{
    
    private float moveSpeed;//摄像机的移动速度
    public GameObject Eye;
    void Start()
    {
        moveSpeed = 2;
    }

    Vector3 rot = new Vector3(0, 0, 0);

    void Update()
    {
            //鼠键控制移动
            WASD();

        if ( Input.anyKey )
        {
            this.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;

        }
        else
        {
            this.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
        }
    }

    /// <summary>
    /// 鼠键控制player移动
    /// </summary>
    void WASD()
    {
        if (Input.GetMouseButton(1))
        {
            if ( Input.GetAxis("Mouse X") != 0 )
            {
                //Debug.Log(Input.GetAxis("Mouse X"));
                if ( Input.GetAxis("Mouse X") < 0.1f && Input.GetAxis("Mouse X") > -0.1f )
                {         
                   // return;
                }
                this.gameObject.transform.Rotate(new Vector3(0, Input.GetAxis("Mouse X") * Time.fixedDeltaTime * 200, 0));//摄像机的旋转速度
                //clearArrow(false);
            }
            if ( Input.GetAxis("Mouse Y") != 0 )
            {
                if ( Input.GetAxis("Mouse Y") < 0.1f && Input.GetAxis("Mouse Y") > -0.1f )
                {
                    Debug.Log("返回");
                  //  return;
                }
                Eye.transform.Rotate(new Vector3(Input.GetAxis("Mouse Y") * Time.fixedDeltaTime * -200, 0, 0));//摄像机的旋转速度
            }
        }
        if (Input.GetKey(KeyCode.W))
        {
            gameObject.transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);    
        }
        if (Input.GetKey(KeyCode.S))
        {
            gameObject.transform.Translate(-Vector3.forward * Time.deltaTime * moveSpeed); 
        }

        if (Input.GetKey(KeyCode.A))
        {
            gameObject.transform.Translate(-Vector3.right * Time.deltaTime * moveSpeed);    
        }
        if (Input.GetKey(KeyCode.D))
        {
            gameObject.transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);         
        }        
    }    
}
  • 13
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值