简体   繁体   English

Unity中如何给相机的边缘碰撞

[英]How to give the camera's edge collision in Unity

I am making a 2D game in Unity, and in this game, the camera will not need to move.我正在 Unity 中制作 2D 游戏,在这个游戏中,相机不需要移动。 As such, I would like to constrain the player's movement within the camera border, preferably with collision instead of just based on the player's transform.因此,我想限制玩家在相机边界内的移动,最好是通过碰撞而不是仅仅基于玩家的变换。 Honestly, I have no idea where to start doing something like this, but I assume it would involve some scripting.老实说,我不知道从哪里开始做这样的事情,但我认为它会涉及一些脚本。 I am pretty comfortable with scripting at this point, but if your answer includes scripting, I would appreciate it if it would include thorough explanations of everything that is going on.在这一点上,我对编写脚本非常满意,但是如果您的答案包括脚本,如果它包含对正在发生的所有事情的详尽解释,我将不胜感激。 By the by, I am using C#.顺便说一句,我正在使用 C#。

If the camera is in orthographic mode, you can useEdgeCollider2D to do this, finding the world positions of the corners of the screen using ScreenToWorldPoint to then determine the shape of the EdgeCollider2D .如果相机处于正交模式,您可以使用EdgeCollider2D来执行此操作,使用 ScreenToWorldPoint 找到屏幕角的世界位置,然后确定ScreenToWorldPointEdgeCollider2D

The Unity Community UnityLibrary Github has an example (copied below): Unity 社区 UnityLibrary Github一个示例(复制如下):

// adds EdgeCollider2D colliders to screen edges
// only works with orthographic camera

using UnityEngine;
using System.Collections;

namespace UnityLibrary
{
  public class ScreenEdgeColliders : MonoBehaviour 
  {
    void Awake () 
    {
      AddCollider();
    }

    void AddCollider () 
    {
      if (Camera.main==null) {Debug.LogError("Camera.main not found, failed to create edge colliders"); return;}

      var cam = Camera.main;
      if (!cam.orthographic) {Debug.LogError("Camera.main is not Orthographic, failed to create edge colliders"); return;}

      var bottomLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, 0, cam.nearClipPlane));
      var topLeft = (Vector2)cam.ScreenToWorldPoint(new Vector3(0, cam.pixelHeight, cam.nearClipPlane));
      var topRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, cam.pixelHeight, cam.nearClipPlane));
      var bottomRight = (Vector2)cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, 0, cam.nearClipPlane));

      // add or use existing EdgeCollider2D
      var edge = GetComponent<EdgeCollider2D>()==null?gameObject.AddComponent<EdgeCollider2D>():GetComponent<EdgeCollider2D>();

      var edgePoints = new [] {bottomLeft,topLeft,topRight,bottomRight, bottomLeft};
      edge.points = edgePoints;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM