Unity环绕物体的摄像机,添加了遮挡的适应

2024-05-24 07:52

本文主要是介绍Unity环绕物体的摄像机,添加了遮挡的适应,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

第三人人称摄像机

支持的功能

设定目标后使用鼠标可以环绕目标点旋转,且会进行遮挡的适配,当有遮挡的时候会移动差值移动到没有遮挡的位置。

使用方式

vThirdPersonCamera 挂在与摄像机上然后为target赋值。
如果有需要检测遮挡的层级可以修改:cullingLayer
vExtensions 创建并复制代码即可,工具类。
如果高度有偏移就修改:height

请添加图片描述

using Invector;
using UnityEngine;public class vThirdPersonCamera : MonoBehaviour
{#region inspector properties    public Transform target;[Tooltip("Leep的速度")]public float smoothCameraRotation = 12f;[Header("遮挡的层")] public LayerMask cullingLayer = 1 << 0;[Tooltip("Debug purposes, lock the camera behind the character for better align the states")]public bool lockCamera;[Header("Camera Input")]public string rotateCameraXInput = "Mouse X";public string rotateCameraYInput = "Mouse Y";[Header("向右偏移角度")]public float rightOffset = 0f;[Header("距离目标的距离")]public float defaultDistance = 2.5f;public float height = 1.4f;public float smoothFollow = 10f;public float xMouseSensitivity = 3f;public float yMouseSensitivity = 3f;public float yMinLimit = -40f;public float yMaxLimit = 80f;#endregion#region hide properties    [HideInInspector]public int indexList, indexLookPoint;[HideInInspector]public float offSetPlayerPivot;[HideInInspector]public string currentStateName;[HideInInspector]public Transform currentTarget;[HideInInspector]public Vector2 movementSpeed;private Transform targetLookAt;private Vector3 currentTargetPos;private Vector3 lookPoint;private Vector3 current_cPos;private Vector3 desired_cPos;private Camera _camera;private float distance = 5f;private float mouseY = 0f;private float mouseX = 0f;private float currentHeight;private float cullingDistance;private float checkHeightRadius = 0.4f;private float clipPlaneMargin = 0f;private float forward = -1f;private float xMinLimit = -360f;private float xMaxLimit = 360f;private float cullingHeight = 0.2f;private float cullingMinDist = 0.1f;#endregionprivate void Start(){Init();}private void Init(){if (target == null)return;_camera = GetComponent<Camera>();currentTarget = target;currentTargetPos = new Vector3(currentTarget.position.x, currentTarget.position.y + offSetPlayerPivot, currentTarget.position.z);targetLookAt = new GameObject("targetLookAt").transform;targetLookAt.position = currentTarget.position;targetLookAt.hideFlags = HideFlags.HideInHierarchy;targetLookAt.rotation = currentTarget.rotation;mouseY = currentTarget.eulerAngles.x;mouseX = currentTarget.eulerAngles.y;distance = defaultDistance;currentHeight = height;}private void FixedUpdate(){if (target == null || targetLookAt == null){return;}//收到鼠标的输入var Y = Input.GetAxis(rotateCameraYInput);var X = Input.GetAxis(rotateCameraXInput);//旋转摄像机RotateCamera(X, Y);CameraMovement();}private void SetMainTarget(Transform newTarget){target = newTarget;currentTarget = newTarget;mouseY = currentTarget.rotation.eulerAngles.x;mouseX = currentTarget.rotation.eulerAngles.y;Init();}/// <summary>/// Camera Rotation behaviour/// </summary>/// <param name="x"></param>/// <param name="y"></param>private void RotateCamera(float x, float y){// free rotation mouseX += x * xMouseSensitivity;mouseY -= y * yMouseSensitivity;movementSpeed.x = x;movementSpeed.y = -y;if (!lockCamera){mouseY = Invector.vExtensions.ClampAngle(mouseY, yMinLimit, yMaxLimit);mouseX = Invector.vExtensions.ClampAngle(mouseX, xMinLimit, xMaxLimit);}else{mouseY = currentTarget.root.localEulerAngles.x;mouseX = currentTarget.root.localEulerAngles.y;}}/// <summary>/// Camera behaviour/// </summary>    private void CameraMovement(){if (currentTarget == null)return;distance = Mathf.Lerp(distance, defaultDistance, smoothFollow * Time.deltaTime);cullingDistance = Mathf.Lerp(cullingDistance, distance, Time.deltaTime);var camDir = (forward * targetLookAt.forward) + (rightOffset * targetLookAt.right);camDir = camDir.normalized;var targetPos = new Vector3(currentTarget.position.x, currentTarget.position.y + offSetPlayerPivot, currentTarget.position.z);currentTargetPos = targetPos;desired_cPos = targetPos + new Vector3(0, height, 0);current_cPos = currentTargetPos + new Vector3(0, currentHeight, 0);RaycastHit hitInfo;ClipPlanePoints planePoints = _camera.NearClipPlanePoints(current_cPos + (camDir * (distance)), clipPlaneMargin);ClipPlanePoints oldPoints = _camera.NearClipPlanePoints(desired_cPos + (camDir * distance), clipPlaneMargin);//Check if Height is not blocked if (Physics.SphereCast(targetPos, checkHeightRadius, Vector3.up, out hitInfo, cullingHeight + 0.2f, cullingLayer)){var t = hitInfo.distance - 0.2f;t -= height;t /= (cullingHeight - height);cullingHeight = Mathf.Lerp(height, cullingHeight, Mathf.Clamp(t, 0.0f, 1.0f));}//Check if desired target position is not blocked       if (CullingRayCast(desired_cPos, oldPoints, out hitInfo, distance + 0.2f, cullingLayer, Color.blue)){distance = hitInfo.distance - 0.2f;if (distance < defaultDistance){var t = hitInfo.distance;t -= cullingMinDist;t /= cullingMinDist;currentHeight = Mathf.Lerp(cullingHeight, height, Mathf.Clamp(t, 0.0f, 1.0f));current_cPos = currentTargetPos + new Vector3(0, currentHeight, 0);}}else{currentHeight = height;}//Check if target position with culling height applied is not blockedif (CullingRayCast(current_cPos, planePoints, out hitInfo, distance, cullingLayer, Color.cyan)) distance = Mathf.Clamp(cullingDistance, 0.0f, defaultDistance);var lookPoint = current_cPos + targetLookAt.forward * 2f;lookPoint += (targetLookAt.right * Vector3.Dot(camDir * (distance), targetLookAt.right));targetLookAt.position = current_cPos;Quaternion newRot = Quaternion.Euler(mouseY, mouseX, 0);targetLookAt.rotation = Quaternion.Slerp(targetLookAt.rotation, newRot, smoothCameraRotation * Time.deltaTime);transform.position = current_cPos + (camDir * (distance));var rotation = Quaternion.LookRotation((lookPoint) - transform.position);transform.rotation = rotation;movementSpeed = Vector2.zero;}/// <summary>/// Custom Raycast using NearClipPlanesPoints/// </summary>/// <param name="_to"></param>/// <param name="from"></param>/// <param name="hitInfo"></param>/// <param name="distance"></param>/// <param name="cullingLayer"></param>/// <returns></returns>private bool CullingRayCast(Vector3 from, Invector.ClipPlanePoints _to, out RaycastHit hitInfo, float distance, LayerMask cullingLayer, Color color){bool value = false;if (Physics.Raycast(from, _to.LowerLeft - from, out hitInfo, distance, cullingLayer)){value = true;cullingDistance = hitInfo.distance;}if (Physics.Raycast(from, _to.LowerRight - from, out hitInfo, distance, cullingLayer)){value = true;if (cullingDistance > hitInfo.distance) cullingDistance = hitInfo.distance;}if (Physics.Raycast(from, _to.UpperLeft - from, out hitInfo, distance, cullingLayer)){value = true;if (cullingDistance > hitInfo.distance) cullingDistance = hitInfo.distance;}if (Physics.Raycast(from, _to.UpperRight - from, out hitInfo, distance, cullingLayer)){value = true;if (cullingDistance > hitInfo.distance) cullingDistance = hitInfo.distance;}return hitInfo.collider && value;}
}
using System;
using System.Collections.Generic;
using UnityEngine;namespace Invector
{public static class vExtensions{public static T[] Append<T>(this T[] arrayInitial, T[] arrayToAppend){if (arrayToAppend == null){throw new ArgumentNullException("The appended object cannot be null");}if ((arrayInitial is string) || (arrayToAppend is string)){throw new ArgumentException("The argument must be an enumerable");}T[] ret = new T[arrayInitial.Length + arrayToAppend.Length];arrayInitial.CopyTo(ret, 0);arrayToAppend.CopyTo(ret, arrayInitial.Length);return ret;}public static T[] vToArray<T>(this List<T> list){T[] array = new T[list.Count];if (list == null || list.Count == 0) return array;for (int i = 0; i < list.Count; i++){array[i] = list[i];}return array;}public static float ClampAngle(float angle, float min, float max){do{if (angle < -360)angle += 360;if (angle > 360)angle -= 360;} while (angle < -360 || angle > 360);return Mathf.Clamp(angle, min, max);}public static ClipPlanePoints NearClipPlanePoints(this Camera camera, Vector3 pos, float clipPlaneMargin){var clipPlanePoints = new ClipPlanePoints();var transform = camera.transform;var halfFOV = (camera.fieldOfView / 2) * Mathf.Deg2Rad;var aspect = camera.aspect;var distance = camera.nearClipPlane;var height = distance * Mathf.Tan(halfFOV);var width = height * aspect;height *= 1 + clipPlaneMargin;width *= 1 + clipPlaneMargin;clipPlanePoints.LowerRight = pos + transform.right * width;clipPlanePoints.LowerRight -= transform.up * height;clipPlanePoints.LowerRight += transform.forward * distance;clipPlanePoints.LowerLeft = pos - transform.right * width;clipPlanePoints.LowerLeft -= transform.up * height;clipPlanePoints.LowerLeft += transform.forward * distance;clipPlanePoints.UpperRight = pos + transform.right * width;clipPlanePoints.UpperRight += transform.up * height;clipPlanePoints.UpperRight += transform.forward * distance;clipPlanePoints.UpperLeft = pos - transform.right * width;clipPlanePoints.UpperLeft += transform.up * height;clipPlanePoints.UpperLeft += transform.forward * distance;return clipPlanePoints;}}public struct ClipPlanePoints{public Vector3 UpperLeft;public Vector3 UpperRight;public Vector3 LowerLeft;public Vector3 LowerRight;}
}

这篇关于Unity环绕物体的摄像机,添加了遮挡的适应的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/997818

相关文章

C#中图片如何自适应pictureBox大小

《C#中图片如何自适应pictureBox大小》文章描述了如何在C#中实现图片自适应pictureBox大小,并展示修改前后的效果,修改步骤包括两步,作者分享了个人经验,希望对大家有所帮助... 目录C#图片自适应pictureBox大小编程修改步骤总结C#图片自适应pictureBox大小上图中“z轴

使用C#如何创建人名或其他物体随机分组

《使用C#如何创建人名或其他物体随机分组》文章描述了一个随机分配人员到多个团队的代码示例,包括将人员列表随机化并根据组数分配到不同组,最后按组号排序显示结果... 目录C#创建人名或其他物体随机分组此示例使用以下代码将人员分配到组代码首先将lstPeople ListBox总结C#创建人名或其他物体随机分组

Unity Post Process Unity后处理学习日志

Unity Post Process Unity后处理学习日志 在现代游戏开发中,后处理(Post Processing)技术已经成为提升游戏画面质量的关键工具。Unity的后处理栈(Post Processing Stack)是一个强大的插件,它允许开发者为游戏场景添加各种视觉效果,如景深、色彩校正、辉光、模糊等。这些效果不仅能够增强游戏的视觉吸引力,还能帮助传达特定的情感和氛围。 文档

Unity协程搭配队列开发Tips弹窗模块

概述 在Unity游戏开发过程中,提示系统是提升用户体验的重要组成部分。一个设计良好的提示窗口不仅能及时传达信息给玩家,还应当做到不干扰游戏流程。本文将探讨如何使用Unity的协程(Coroutine)配合队列(Queue)数据结构来构建一个高效且可扩展的Tips弹窗模块。 技术模块介绍 1. Unity协程(Coroutines) 协程是Unity中的一种特殊函数类型,允许异步操作的实现

Unity 资源 之 Super Confetti FX:点亮项目的璀璨粒子之光

Unity 资源 之 Super Confetti FX:点亮项目的璀璨粒子之光 一,前言二,资源包内容三,免费获取资源包 一,前言 在创意的世界里,每一个细节都能决定一个项目的独特魅力。今天,要向大家介绍一款令人惊艳的粒子效果包 ——Super Confetti FX。 二,资源包内容 💥充满活力与动态,是 Super Confetti FX 最显著的标签。它宛如一位

Unity数据持久化 之 一个通过2进制读取Excel并存储的轮子(4)

本文仅作笔记学习和分享,不用做任何商业用途 本文包括但不限于unity官方手册,unity唐老狮等教程知识,如有不足还请斧正​​ Unity数据持久化 之 一个通过2进制读取Excel并存储的轮子(3)-CSDN博客  这节就是真正的存储数据了   理清一下思路: 1.存储路径并检查 //2进制文件类存储private static string Data_Binary_Pa

Unity Adressables 使用说明(一)概述

使用 Adressables 组织管理 Asset Addressables 包基于 Unity 的 AssetBundles 系统,并提供了一个用户界面来管理您的 AssetBundles。当您使一个资源可寻址(Addressable)时,您可以使用该资源的地址从任何地方加载它。无论资源是在本地应用程序中可用还是存储在远程内容分发网络上,Addressable 系统都会定位并返回该资源。 您

240907-Gradio插入Mermaid流程图并自适应浏览器高度

A. 最终效果 B. 示例代码 import gradio as grmermaid_code = """<iframe srcdoc='<!DOCTYPE html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Spa

行为智能识别摄像机

行为智能识别摄像机 是一种结合了人工智能技术和监控摄像技术的先进设备,它能够通过深度学习算法对监控画面进行实时分析,自动识别和分析监控画面中的各种行为动作。这种摄像机在安防领域有着广泛的应用,可以帮助监控人员及时发现异常行为,并采取相应的措施。 行为智能识别摄像机可以有效预防盗窃事件。在商场、超市等公共场所安装这种摄像机,可以通过识别异常行为等情况,及时报警并阻止不安全行为的发生

Unity Adressables 使用说明(六)加载(Load) Addressable Assets

【概述】Load Addressable Assets Addressables类提供了加载 Addressable assets 的方法。你可以一次加载一个资源或批量加载资源。为了识别要加载的资源,你需要向加载方法传递一个键或键列表。键可以是以下对象之一: Address:包含你分配给资源的地址的字符串。Label:包含分配给一个或多个资源的标签的字符串。AssetReference Obj