如何只检测单向碰撞?

时间:2014-08-20 01:00:42

标签: unity3d collision game-physics

好的,那么就说你正在尝试制作像Super Smash Bros这样的游戏。如何制作它以便你可以跳起来并通过一个浮动平台,但同时也让你无法在Unity 3d中完成它?

1 个答案:

答案 0 :(得分:0)

将此C#脚本附加到您的平台,您可以选择是否允许玩家仅跳过您的平台(topCollision = true)或仅通过您的平台(topCollision = false)。此外,您的平台必须具有网格对撞机才能使脚本正常工作。取自http://answers.unity3d.com/questions/236313/one-way-collider.html

using UnityEngine;
using System.Collections.Generic;

[RequireComponent (typeof (MeshCollider))]
public class PlatformCollision : MonoBehaviour
{
    public bool topCollision = true;
    public float maxAngle = 45.0f;

    void Start ()
    {
        float cos = Mathf.Cos(maxAngle);
        MeshCollider MC = GetComponent<MeshCollider>();
        if (MC == null)
        {
            Debug.LogError("PlatformCollision needs a MeshCollider");
            return;
        }
        Mesh M = new Mesh();
        Vector3[] verts = MC.sharedMesh.vertices;
        List<int> triangles = new List<int>(MC.sharedMesh.triangles);
        for (int i = triangles.Count-1; i >=0 ; i -= 3)
        {
            Vector3 P1 = transform.TransformPoint(verts[triangles[i-2]]);
            Vector3 P2 = transform.TransformPoint(verts[triangles[i-1]]);
            Vector3 P3 = transform.TransformPoint(verts[triangles[i  ]]);
            Vector3 faceNormal = Vector3.Cross(P3-P2,P1-P2).normalized;
            if ( (topCollision && Vector3.Dot(faceNormal, Vector3.up) <= cos) ||
                 (!topCollision && Vector3.Dot(faceNormal, -Vector3.up) <= cos) )
            {
                triangles.RemoveAt(i);
                triangles.RemoveAt(i-1);
                triangles.RemoveAt(i-2);
            }
        }
        M.vertices = verts;
        M.triangles = triangles.ToArray();
        MC.sharedMesh = M;
    }
}