首页 > 解决方案 > 游戏中的所有枪都同时射击,而我只想要我拿着的枪射击

问题描述

在此处输入图像描述

我的问题是,当我拿着枪射击时,地板上的所有其他枪也开始射击。我怎样才能做到只有我用鼠标拿着的枪才能射击?

你用鼠标左键拿起枪,然后用右键射击

我的取货代码

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

public class PickUp : MonoBehaviour
{
    bool Pressed = false;

    void OnMouseDown()
    {
        Pressed = true;
        GetComponent<Rigidbody2D>().isKinematic = true;
    }
 
    void OnMouseUp()
    {
        Pressed = false;
        GetComponent<Rigidbody2D>().isKinematic = false;
    }
 
    void Update()
    {
        if(Pressed)
        {
            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            transform.position = mousePos;
        }
    }
}

我的枪代码

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

public class Weapon : MonoBehaviour{

       public Transform firePoint;
       public float fireRate = 15f;
       public GameObject bulletPrefab;
       public Transform  MuzzleFlashPrefab;

       private float nextTimeToFire = 0f;
       
   
    
    void Update() {


        

        if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
        {
            nextTimeToFire = Time.time + 1f/fireRate;
            Shoot();
              
        }
    }


     void Shoot ()
    {
        Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
         Transform clone = Instantiate (MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
       clone.parent = firePoint;
       float size = Random.Range (0.02f, 0.025f);
       
       clone.localScale = new Vector3 (size, size, size);
       Destroy (clone.gameObject, 0.056f);
    }

 
}



  

和我的子弹代码

using System.Collections.Generic;
using UnityEngine;

public class bulet : MonoBehaviour
{
    
    
    public float speed = 40f;
    public Rigidbody2D rb;

  
    // Start is called before the first frame update
    void Start()
    {
        rb.velocity = transform.right * speed;
    }
}

标签: c#unity3d

解决方案


在你的武器中设置一个名为 like 的标志pickedUp,并在拾取/放下武器时切换它。然后在您的武器更新功能中,检查您是否应该根据其拾取状态处理该武器的输入。如果它没有被拾起,则无需检查它是否应该发射子弹。


推荐阅读