[英]How to cut two objects of the same type Unity2D
这是我进行的快速键入,目的是让您了解您可以做什么。
在您的场景中创建一个空的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.