我做了一个3d游戏,我有一个第一人称控制器,由操纵杆控制。我希望我的播放器只有在我触摸屏幕上的按钮时才能拍摄,但现在我的播放器在我触摸屏幕上的任何东西时都会拍摄。以下是拍摄函数的脚本:
using UnityEngine;
using UnityEngine.UI;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public Button button;
// Start is called before the first frame update
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
button.onClick.AddListener(TaskOnClick);
}
// Update is called once per frame
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);
}
void Shoot()
{
RaycastHit hit;
if( Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(damage);
}
}
}
void OnCollisionEnter(Collision collision)
{
Debug.DrawRay(collision.contacts[0].point, collision.contacts[0].normal, Color.green, 2, false);
}
void TaskOnClick()
{
Shoot();
}
}
发布于 2019-05-15 21:54:33
每当您按下"Fire1“按钮时,您的Shoot()
方法就会运行,因为您所做的唯一检查是是否为(Input.GetButtonDown("Fire1"))
。
如果您希望依赖一个按钮来触发,则需要删除这部分代码,并在单击该按钮时调用Shoot()
。
您可以使用代码将事件添加到按钮,如here所述
public Button m_YourFirstButton;
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
m_YourFirstButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
//Output this to console when Button1 or Button3 is clicked
Debug.Log("You have clicked the button!");
}
或者你可以通过引用你的枪的monobehaviour来调用它。
https://stackoverflow.com/questions/56150831
复制相似问题