在Unity中单击并拖动时触发另一个对象上的脚本

时间:2015-12-18 06:39:01

标签: c# unity3d unity3d-2dtools unity5

我正在做一个2D项目,我已经添加了一个精灵作为拍摄按钮。这个按钮工作正常。附带的脚本是:(我向精灵添加了一个盒子对撞机)

using UnityEngine;
using System.Collections;

public class ClickScript : MonoBehaviour {
    public shootTest _shooterScript;

    // Use this for initialization
    void Start () {

    }

    void LoadScript()
    {
        _shooterScript.ShootRock();
    }


    // Update is called once per frame
    void Update () {
        if(Input.GetMouseButtonDown(0)){
            Vector2 mousePosition = new Vector2();
            mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Collider2D hitCollider = new Collider2D();
            hitCollider = this.collider2D;
        hitCollider = Physics2D.OverlapPoint(mousePosition);

            Debug.Log("mouse pos "+mousePosition.x+" y "+mousePosition.y+" ");    


            if(hitCollider){
                LoadScript();
                Debug.Log("Hit "+hitCollider.transform.name+" x"+hitCollider.transform.position.x+" y "+hitCollider.transform.position.y);    
            }
    }
}}

然后我添加了一个十字准线,以便能够计算瞄准的方向。这是单击并拖动对象的脚本。在这个对象上圆圈Colider 2D。

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(MeshCollider))]

public class Aim : MonoBehaviour 
{

    private Vector3 screenPoint;
    private Vector3 offset;

    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);

        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));

    }

    void OnMouseDrag()
    {

        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint)+offset;
        this.transform.position = curPosition;

    }

}

当我添加此瞄准脚本并单击十字准线拖动它时,拍摄脚本会消失。

我对团结很新,所以我假设它很简单。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我将点击脚本中的更新功能更改为

void Update () {
    if(Input.GetMouseButtonDown(0)){
        Vector2 mousePosition = new Vector2();
        mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);


        if(this.collider2D.OverlapPoint(mousePosition)){
            LoadScript();

        }
}

因此,只有在单击该特定对象时才会触发。也许有一种更清洁的方式,但这很有效。