簡體   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