问题描述
我的问题是,当我拿着枪射击时,地板上的所有其他枪也开始射击。我如何做到只有我用鼠标拿着的枪才能射击?
鼠标左键拿起枪,右键射击
我的取货码
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.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;
}
}
解决方法
在您的武器中设置一个标记,称为喜欢 pickedUp
,并在拿起/放下武器时切换它。然后在您的武器更新功能中,检查您是否应该根据其拾取状态处理该武器的输入。如果它没有被捡起,就没有必要检查它是否应该发射子弹。