在显示的任何位置生成 ClickMouseButton(0) [英] Generate ClickMouseButton(0) anywhere on display

查看:28
本文介绍了在显示的任何位置生成 ClickMouseButton(0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的脚本:

void Update () {
    public float clickTimer = 2f;
    clickTimer -= Time.deltaTime;
    if(clickTimer <= 0){
        //"Generate Click" I try: Input.GetMouseButtonDown(0);
        clickTimer = 2f;
    }
}

我不想点击任何特定对象,因为我有 RayCastHit 并且我想在显示的任何地方生成点击.

I don't want to click any specific object because I have RayCastHit and I want to generate click anywhere on display.

推荐答案

使用此脚本(用于 2D 游戏),您可以从屏幕上用鼠标单击的点创建 RayCast,并检查您使用的游戏对象打了.我建议您首先标记您想要点击的任何游戏对象

With this script (which is for 2D games) you can create a RayCast from the point in the screen where you clicked with the mouse, and check what GameObjects you have hit. I recommend you to tag first any GameObject you want to be clicked

void Update () {

    clickTimer -= Time.deltaTime;

    if(clickTimer <= 0){

        if(Input.GetMouseButtonDown(0)) {

            //What point was pressed
            Vector3 worldPoint = Camera.main.ScreenToWorldPoint( Input.mousePosition );
            worldPoint.z = Camera.main.transform.position.z;
            //Generate a Ray from the position you clicked in the screen
            Ray ray = new Ray( worldPoint, new Vector3( 0, 0, 1 ) );
            //Cast the ray to hit elements in your scene
            RaycastHit2D hit = Physics2D.GetRayIntersection( ray );

            if(hit.collider != null) {
                 Debug.Log("I hit: "+hit.gameObject.tag);
                //And here you can check what GameObject was hit

                if(hit.gameObject.tag == "AnyTag"){
                     //Here you can do whatever you need for AnyTag objects
                }
            }
        }   

        clickTimer = 2f;
    }
}

这篇关于在显示的任何位置生成 ClickMouseButton(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆