给unity酱复刻了个原神相机视角

发布于:2023-01-22 ⋅ 阅读:(457) ⋅ 点赞:(0)

寒假在家闲着无聊写的,留个代码,防止忘记
在这里插入图片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class f_mc : MonoBehaviour
{
    public Transform player;   //游戏角色
    public GameObject asso;  //LookAt函数的基准
    public float spinSpeed = 512;   //水平转速
    public float scale_mul = 128;  //画面缩放倍率
    public float Yaxis_mul=0.02f;   //垂直升降倍率
    Vector3 setoff;  //相机跟随基本辅助变量
    // Start is called before the first frame update
    void Start()
    {
        Cursor.visible = false;   //隐藏鼠标
        setoff = transform.position - player.position;   //初始化setoff
    }

    // Update is called once per frame
    void Update()
    {
        //控制画面缩放
        float scale = Input.GetAxis("Mouse ScrollWheel");  
        if (scale > 0 && Camera.main.fieldOfView < 100 || scale < 0 && Camera.main.fieldOfView > 50)
        {
            Camera.main.fieldOfView += scale * scale_mul;  
        }
        //控制相机绕游戏角色为轴旋转
        float X = Input.GetAxis("Mouse X");  
        Quaternion spin = Quaternion.AngleAxis(X * spinSpeed * Time.deltaTime, player.up);
        transform.position = spin * setoff + player.position;
        //用相机垂直升降简略实现角色上下视角
        float Y = Input.GetAxis("Mouse Y");
        float Yincrement = -Y * Yaxis_mul;       
        if (Y > 0 && transform.position.y + Yincrement > 16.8 || Y < 0 && transform.position.y + Yincrement < 21.2)
        {
            transform.position += new Vector3(0, Yincrement, 0);
        }
        //每轮update必须更新setoff
        setoff = transform.position - player.position;
        transform.LookAt(asso.transform.position);
    }
}

本文含有隐藏内容,请 开通VIP 后查看