繁体   English   中英

如何剪切相同类型Unity2D的两个对象

[英]How to cut two objects of the same type Unity2D

我有个问题。 我有一些来自左右随机的对象。 当两个相同种类的物体重叠时,我可以将它们切开。 剪切img源

这些对象包含BoxCollider2D和RigidBody2D。

我确实是随机来的,但是现在我该怎么做才能削减他们,有人知道我可以做什么吗? 非常感谢你 。

这是我进行的快速键入,目的是让您了解您可以做什么。

在您的场景中创建一个空的GameObject,为其提供LineRenderer,将其位置计数设置为0(这将防止在单击播放器之前渲染它。)将此脚本附加到该对象上。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Slash : MonoBehaviour 
{
    LineRenderer myRenderer;
    public float mouseZ = -2f;
    Vector3[] positions = new Vector3[2] {Vector3.zero, Vector3.zero};

    void Start() 
    {
        myRenderer = this.getComponent<LineRenderer>();
    }

    void Update() 
    { 
        UpdateMouse();
    }

    void UpdateMouse() 
    {
        if(Input.GetMouseButtonDown(0)) 
        {
            UpdatePositions(0);
        }
        else if(Input.GetMouseButton(0)) 
        {
            UpdatePositions(1);
        } 
        else if(Input.GetMouseButtonUp(0)) 
        {
             UpdatePositions(1);
             HandleCollisions();
        }
    }

    Vector3 GetNewPosition() 
    {
        // Method assumes you are using an orthographic camera.
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePositions);
        // Set the Z position so we can see it from the camera (it would use the same z as the camera otherwise)
        mousePosition.z = mouseZ;
        return mousePosition;
    }

    void updatePositions(int index) 
    {
         if(index >= positions.Length) 
         {
             Debug.LogError("Invalid index was given: " + index);
             return;
         }

         positions[index] = GetNewPosition();
         myRenderer.positionCount = index + 1;
         myRenderer.SetPositions(positions);

    }

    void HandleCollisions() 
    {
        RaycastHit2D[] rays = Physics2D.LinecastAll(positions[0], positions[1]);

        if(rays != null && rays.length > 1) 
        {
            // Checking only the first and second indices of the array, if you want to allow
            // The users to collide with multiple objects this is where you would change that logic.
            // Using name for now, but may be better if you compared them via tag, layer, or gave them a script that defined their type.
             if(rays[0].collider.gameObject.name.Equals(rays[1].collider.gameObject.name)) 
             {
                  rays[0].collider.gameObject.SetActive(false);
                  rays[1].collider.gameObject.SetActive(false);
             }
        }
        positions = new Vector3[2] {Vector3.zero, Vector3.zero};
    }

}

请花一些时间来了解此脚本的功能,然后根据您的需要对其进行自定义。

暂无
暂无

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

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