我正在尝试为我的游戏创建一个EdgeCollider2D
脚本。从下面的代码可以看出它覆盖了主摄像头左右两端的一部分。左侧壁工作,防止物体向左移动,但右侧墙不能防止物体离开屏幕。我不太确定导致它的原因。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameEdgeScript : MonoBehaviour {
// lets make verticies for the edge collider 2d
List<Vector2> newVerticies = new List<Vector2>();
EdgeCollider2D col;
// Use this for initialization
void Awake () {
col = gameObject.AddComponent<EdgeCollider2D>();
Camera camera = GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<Camera> ();
Vector3 screenSize = camera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, camera.nearClipPlane));
float height1 = GameObject.FindGameObjectWithTag ("spriteHigh").GetComponent<SpriteRenderer> ().sprite.rect.height/2;
float height2 = Screen.height*((float)0.8) + GameObject.FindGameObjectWithTag ("spriteLow").GetComponent<SpriteRenderer> ().sprite.rect.height/2;
newVerticies.Add( (Vector2)camera.ScreenToWorldPoint(new Vector3(0, height1, camera.nearClipPlane)));
newVerticies.Add( (Vector2)camera.ScreenToWorldPoint(new Vector3(0, height2, camera.nearClipPlane)));
newVerticies.Add( (Vector2)camera.ScreenToWorldPoint(new Vector3(Screen.width, height2, camera.nearClipPlane))); // NOT BLOCKING OBJECTS AT THE RIGHT X VALUE (Screen.width)
newVerticies.Add( (Vector2)camera.ScreenToWorldPoint(new Vector3(Screen.width, height1, camera.nearClipPlane)));// NOT BLOCKING OBJECTS AT THE RIGHT X VALUE (Screen.width)
Debug.Log (Screen.width);
getPointsToDebug ();
setPoints ();
for (int i = 0; i<col.points.Length; i++) {
Debug.Log (col.points[i]);
}
void getPointsToDebug() {
foreach (Vector2 piste in col.points) {
Debug.Log(piste);
}
}
void setPoints() {
col.points = newVerticies.ToArray();
}
}