【问题标题】:Unity 2D: Check if sprites overlap (c#)Unity 2D:检查精灵是否重叠(c#)
【发布时间】:2020-07-24 16:19:57
【问题描述】:

我正在 2D Unity 中制作一个小型匹配迷你游戏,玩家可以在其中拖放同一类别的不同图像(精灵)。我制作了一个运行良好的拖放脚本,但我不确定如何检查图像是否放置在正确的位置。如果图像匹配不正确,我希望玩家拖过的图像变回原来的位置。如果图像正确匹配,我希望两者都消失。如何检查图像是否重叠。

拖放脚本:

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

public class DragandDrop : MonoBehaviour {

private bool selected;

private void Update()
{
    //Mouse is held down
   if(selected == true)
    {
        Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(cursorPos.x, cursorPos.y, -1.0f);
    } 

   //Mouse is released
   if(Input.GetMouseButtonUp(0))
    {
        ScoreScript.scoreValue += 1/6f;
        selected = false;
        //Ignore these:
        // Vector3 position = transform.position;
        // position[2] = 0;
        // transform.position = position;


        //This is where I think I should check for overlap
    }

}

void OnMouseOver() {
    if(Input.GetMouseButtonDown(0)) {
        selected = true;
    }
}
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    应该可以的:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ImageScript : MonoBehaviour {
    
    private bool selected;
    Vector3 currentPosition;
    ImageScript secondImage;
    void Update()
    {
        if (selected == true)
        {
        Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(cursorPos.x, cursorPos.y, -1.0f);
    
        } 
    
    //Mouse is released
        if(Input.GetMouseButtonUp(0))
        {
            if (Vector3.Distance(transform.position, secondImage.transform.position) < 1f)
            {
                //Distance to second image is less than 1 on mouse up which makes the both images disappear.
    
                ScoreScript.scoreValue += 1/6f;
                selected = false;
                Destroy(SecondImage);
                Destroy(this);
            }
            else
            {
                //Distance to second image on mouse up is higher than 1 which resets the position back to original.
                transform.position = currentPosition;
            }
            //Ignore these:
            // Vector3 position = transform.position;
            // position[2] = 0;
            // transform.position = position;
    
    
            //This is where I think I should check for overlap
    }
    
    }
    void OnMouseOver() {
    if(Input.GetMouseButtonDown(0)) 
    {
        selected = true;
        currentPosition = transform.position;
        }
    }
    

    确保将第二张图片的ImageScript 分配给当前一张。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多