【发布时间】:2020-02-12 21:32:07
【问题描述】:
我正在尝试制作一个玩家必须移动两个球拍的乒乓球游戏。它们目前被设置为动态 2D 刚体(碰撞检测连续)并附有一个盒子碰撞器(不是触发器)。
问题是桨不会与我在相机上设置的周围盒子碰撞器发生碰撞,使用以下脚本:
using UnityEngine;
using System.Collections;
namespace UnityLibrary
{
public class EdgeCollider : MonoBehaviour
{
public float colDepth = 4f;
public float zPosition = 0f;
private Vector2 screenSize;
private Transform topCollider;
private Transform bottomCollider;
private Transform leftCollider;
private Transform rightCollider;
private Vector3 cameraPos;
// Use this for initialization
void Start () {
//Generate our empty objects
topCollider = new GameObject().transform;
bottomCollider = new GameObject().transform;
rightCollider = new GameObject().transform;
leftCollider = new GameObject().transform;
//Name our objects
topCollider.name = "TopCollider";
bottomCollider.name = "BottomCollider";
rightCollider.name = "RightCollider";
leftCollider.name = "LeftCollider";
//Add the colliders
topCollider.gameObject.AddComponent<BoxCollider2D>();
bottomCollider.gameObject.AddComponent<BoxCollider2D>();
rightCollider.gameObject.AddComponent<BoxCollider2D>();
leftCollider.gameObject.AddComponent<BoxCollider2D>();
//Make them the child of whatever object this script is on, preferably on the Camera so the objects move with the camera without extra scripting
topCollider.parent = transform;
bottomCollider.parent = transform;
rightCollider.parent = transform;
leftCollider.parent = transform;
//Generate world space point information for position and scale calculations
cameraPos = Camera.main.transform.position;
screenSize.x = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0))) * 0.5f;
screenSize.y = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height))) * 0.5f;
//Change our scale and positions to match the edges of the screen...
rightCollider.localScale = new Vector3(colDepth, screenSize.y * 2, colDepth);
rightCollider.position = new Vector3(cameraPos.x + screenSize.x + (rightCollider.localScale.x * 0.5f), cameraPos.y, zPosition);
leftCollider.localScale = new Vector3(colDepth, screenSize.y * 2, colDepth);
leftCollider.position = new Vector3(cameraPos.x - screenSize.x - (leftCollider.localScale.x * 0.5f), cameraPos.y, zPosition);
topCollider.localScale = new Vector3(screenSize.x * 2, colDepth, colDepth);
topCollider.position = new Vector3(cameraPos.x, cameraPos.y + screenSize.y + (topCollider.localScale.y * 0.5f), zPosition);
bottomCollider.localScale = new Vector3(screenSize.x * 2, colDepth, colDepth);
bottomCollider.position = new Vector3(cameraPos.x, cameraPos.y - screenSize.y - (bottomCollider.localScale.y * 0.5f), zPosition);
}
}
}
球与桨碰撞并弹回原样,并与周围的盒子碰撞器碰撞并完美弹回。但是,桨叶会直接穿过周围的盒子碰撞器 (EdgeColliders)。请注意,我使用统一资产商店中的 Touchscript 包来控制移动。它不会移动它使用变换的刚体。另一件需要注意的事情是,当我使桨非常轻(0.0001 质量)并向它们添加重力时,它们确实会与边缘碰撞器发生碰撞并且不会穿过屏幕。
【问题讨论】:
标签: unity3d 2d game-physics rigid-bodies