unity3D实现简单的人物移动加上视角切换

 注1:在此工程中,我用的为此版本

注2:在此项目中,我从UnityStore导入一个可行移动的模型之后,发现其中有材质丢失和包依赖丢失的问题。导致每次导入工程时,都需要重新导入一遍。

一、实现目标 

        实现简单的人物移动加上视角切换,为创建的capsule实现操纵WASD的前后左右移动,并且可以通过按钮点击实现第一人称到第三人称的视角切换。

        此处会联系到前文:

自由视角上帝视角

二、实现方法

第一步:创建capsule,命名为PersonCapsule,并未其添加两个相机,分别命名为TheFirstPersonCamera,TheThirdPersonCamera。

第二步:创建脚本 -- PersonMoving,按如下编辑:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 
/// version - 0.1
/// 用于人物的前后移动与左右视角的旋转。 
/// </summary>
public class PersonMoving : MonoBehaviour
{
    public float Currentspeed = 10;
    private float InterSpeed = 10;
    public float mouseSensitivity = 10;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        Debug.Log("h is:" + h + " v is:" + v);

        transform.Translate(h * Currentspeed * Time.deltaTime,0, v * Currentspeed * Time.deltaTime);
        float mousex = Input.GetAxis("Mouse X") * mouseSensitivity;
        //float mousey = Input.GetAxis("Mouse Y") * mouseSensitivity;
        if (Input.GetMouseButton(1)) // 鼠标右键旋转视角
        {
            //transform.Rotate(0, 0, mousey); // 旋转Y轴
            transform.Rotate(0, mousex, 0, Space.World); // 旋转X轴
        }
        //加速
        if (Input.GetKeyDown(KeyCode.LeftShift))
        {
            Currentspeed = Currentspeed * 5;
        }
        if (Input.GetKeyUp(KeyCode.LeftShift))
        {
            Currentspeed = InterSpeed;
        }



    }
}

第三步:将脚本连接到PersonCapsule

第四步:编写脚本 -- TheThirdPersonCameraSelected

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 
/// version - 0.1
/// 点击Button切换到第三人称相机
/// </summary>
public class TheThirdPersonCameraSelected : MonoBehaviour
{
    public Camera godviewcamera;
    public Camera freecamera;
    public Camera firstpersoncamera;
    public Camera ThirdPersonCamera;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void TheThirdPersonCameraSelectedF()
    {
        godviewcamera.gameObject.SetActive(false);
        freecamera.gameObject.SetActive(false);
        firstpersoncamera.gameObject.SetActive(false);
        ThirdPersonCamera.gameObject.SetActive(true);
    }
}

第五步:将脚本TheThirdPersonCameraSelected连接到第一步中创建的TheThirdPersonCamera上将对应的相机拖到相应的位置。

第六步:创建一个Button -- TheThirdPersonCameraButton,为其添加OnClick()事件。

三、结果测试

        点击”第三人称“按钮,跳转到第三人称相机。


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值