[英]Bullets being fired / created repeatedly without player's input - UNET Unity
場景:創建我的第一個多人游戲並遇到一個奇怪的問題。 這是一款坦克游戲,玩家可以射擊子彈並互相殺死。
您可以充電子彈以使其更快/更遠地射擊。
問題:客戶端播放器充滿電並釋放后,子彈將繼續重復產生,並且永不停止。 如果客戶端播放器未完全充電,則不會發生此問題。
我相信問題是if (m_CurrentLaunchForce >= m_MaxLaunchForce && !m_Fired)
的更新功能
注意:主機播放器沒有此問題,因此與網絡有某種關系。
private void Update()
{
if (!isLocalPlayer)
return;
// Track the current state of the fire button and make decisions based on the current launch force.
m_AimSlider.value = m_MinLaunchForce;
if (m_CurrentLaunchForce >= m_MaxLaunchForce && !m_Fired) {
m_CurrentLaunchForce = m_MaxLaunchForce;
CmdFire ();
} else if (Input.GetButtonDown (m_FireButton) && !m_Fired) {
m_Fired = false;
m_CurrentLaunchForce = m_MinLaunchForce;
m_ShootingAudio.clip = m_ChargingClip;
m_ShootingAudio.Play();
} else if (Input.GetButton (m_FireButton)) {
m_CurrentLaunchForce += m_ChargeSpeed * Time.deltaTime;
m_AimSlider.value = m_CurrentLaunchForce;
} else if (Input.GetButtonUp(m_FireButton)) {
CmdFire ();
}
}
[Command]
private void CmdFire()
{
// Set the fired flag so only Fire is only called once.
m_Fired = true;
// Create an instance of the shell and store a reference to it's rigidbody.
GameObject shellInstance = (GameObject)
Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) ;
// Set the shell's velocity to the launch force in the fire position's forward direction.
shellInstance.GetComponent<Rigidbody>().velocity = m_CurrentLaunchForce * m_FireTransform.forward;
// Change the clip to the firing clip and play it.
m_ShootingAudio.clip = m_FireClip;
m_ShootingAudio.Play ();
NetworkServer.Spawn (shellInstance);
// Reset the launch force. This is a precaution in case of missing button events.
m_CurrentLaunchForce = m_MinLaunchForce;
}
如果仔細閱讀文檔,您會發現-> [Command]函數在與連接關聯的播放器對象上被調用。 通過將播放器objec傳遞給NetworkServer.PlayerIsReady()函數來響應“就緒”消息進行設置。 通過網絡對命令調用的參數進行序列化,以便使用與客戶端上的函數相同的值來調用服務器函數。
我認為它對您不起作用的原因是因為您必須將參數傳遞給類似
[Command]
private void CmdFire(bool m_Fired)
{
// Set the fired flag so only Fire is only called once.
m_Fired = true;
// Create an instance of the shell and store a reference to it's rigidbody.
GameObject shellInstance = (GameObject)
Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) ;
// Set the shell's velocity to the launch force in the fire position's forward direction.
shellInstance.GetComponent<Rigidbody>().velocity = m_CurrentLaunchForce * m_FireTransform.forward;
// Change the clip to the firing clip and play it.
m_ShootingAudio.clip = m_FireClip;
m_ShootingAudio.Play ();
NetworkServer.Spawn (shellInstance);
// Reset the launch force. This is a precaution in case of missing button events.
m_CurrentLaunchForce = m_MinLaunchForce;
}
然后像這樣調用它:
CmdFire(m_Fired),其中m_Fired必須指向玩家自己的變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.