简体   繁体   English

命中脚本针对3d对象而不是2d运行

[英]the hit script run for 3d objects but not 2d

this is the script for my game.but it just works for 3d object like cube and not for 2d images in the game.how to fix it? 这是我的游戏脚本。但是它仅适用于立方体等3D对象,不适用于游戏中的2D图像。如何解决?

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

public class touchinput : MonoBehaviour {
    void Update () {
        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
        {
            Ray ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
            RaycastHit hit;

            if ( Physics.Raycast(Ray, out hit))
            {
                Destroy(hit.collider.gameObject);
            }
        }
    }
}

i try to change to this but i get lots of errors and don't know how to fix. 我尝试更改为此错误,但出现很多错误,并且不知道如何解决。

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

public class touchinput : MonoBehaviour {
    void Update () {
        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
        {
            Ray2D ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
            RaycastHit2D hit;

            if ( Physics2D.Raycast(Ray2D, out hit))
            {
                Destroy(hit.collider.gameObject);
            }
        }
    }
}

Raycast indeed doesn't work on 2D colliders. Raycast确实不适用于2D对撞机。
I found this method the other day, you can try it: 前几天我找到了这种方法,可以尝试一下:

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
    Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
    Vector2 touchPos = new Vector2(wp.x, wp.y);
    if (collider2D == Physics2D.OverlapPoint(touchPos))
    {
        //your code
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM