首页 文章

选择特定的预制件

提问于
浏览
0

我创建了多个相同的预制克隆like that.,我想销毁其中一个我选择的 .

首先,我使用raycast2d来检测命中并使用预制件进行合并

if(Input.GetMouseButtonDown(1))

        {
            RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.mousePosition)), Vector2.zero);
            if(hit.collider != null && hit.collider.gameObject==gameObject){


                health-=PlayerScript.damage;

                if(health<=0){

                    Destroy(hit.collider.gameObject);
                }

            }
        }

这个脚本影响所有预制件的 Health 状况 . 所以我决定使用对撞机创建一个游戏对象,如果这个游戏对象与预制件合并,则预制件会失去 Health 然后销毁 . 我像这样实例化游戏对象

GameObject object=Instantiate(selectOb,Camera.main.ScreenToWorldPoint(Input.mousePosition), Quaternion.identity) as GameObject;

然后我检查游戏对象和预制件之间是否存在与void OnCollision2DEnter()的冲突 .

现在有不同的问题 . 游戏对象没有与其他预制件合并,因为area sizes of collider

我希望,我可以描述我的问题 . 我在等待你关于选择特定预制件或碰撞问题的建议

1 回答

  • 0

    在场景中的游戏对象上这样的东西(可能是作为控制器的空游戏对象):

    请注意,如果使用默认的摄像头方向,则光线投射的方向应为 -Vector2.up .

    public class RayShooter : MonoBehaviour
    {
        void Update()
        {
            if(Input.GetMouseButtonDown(1))     // 1 is rightclick, don't know if you might want leftclick instead
            {
                RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.mousePosition)), -Vector2.up);
                if(hit.collider != null)
                {
                    GameObject target = hit.collider.gameObject;
                    target.GetComponent<Enemy>().dealDamage(PlayerScript.damage);
                    // "Enemy" is the name of the script on the things you shoot
                }
            }
        }
    }
    

    关于你拍摄的东西(这里称为“敌人”):

    public class Enemy : MonoBehaviour
    {
        int health = 10;
    
        public void dealDamage(int value)
        {
            health -= value;
            if(health <= 0)
            {
                Destroy(gameObject);
            }
        }
    }
    

    这将是一个非常基本的设置,显然你要拍摄的东西需要一个对撞机才能工作 . 此外,将图层和图层蒙板包含在光线投射中可能是个好主意 .

相关问题