如何防止玩家在弹药耗尽后射击弹丸
本文关键字:射击 何防止 玩家 | 更新日期: 2023-09-27 18:06:54
我正在制作一款类似于《太空射手》的游戏,我想知道如何防止玩家在弹药耗尽后继续射击。
下面的两个脚本控制我的玩家的移动和行动,并减少当前投射计数每次玩家按空格键。
球员脚本
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
//Movement speed of Player sprite
public float Speed = 20.5f;
//GameObject to store the projectile object
public GameObject Projectile;
// Update is called once per frame
void Update ()
{
//If left arrow key is pressed
if (Input.GetKey (KeyCode.LeftArrow))
//Move the player to the left
transform.Translate (new Vector2 (-Speed * Time.deltaTime, 0f));
//If right arrow key is pressed
if (Input.GetKey (KeyCode.RightArrow))
//Move the player to the right
transform.Translate (new Vector2 (Speed * Time.deltaTime, 0f));
//If the spacebar is pressed
if (Input.GetKeyDown (KeyCode.Space))
{
//Instatiate a new projectile prefab 2 units above the Player sprite
Instantiate (Projectile, transform.position + transform.up * 2, Quaternion.identity);
//Find the game object with the tag "Projectile" and call the DecreaseProjectileCount() function from the ProjectileTracker script
GameObject.FindGameObjectWithTag("Projectile").GetComponent<ProjectileTracker>().DecreaseProjectileCount();
}
}
}
ProjectileTracker脚本
using UnityEngine;
using System.Collections;
public class ProjectileTracker : MonoBehaviour {
//Variable to store the current projectile count
public GameObject ProjectileRef;
//Set the current projectile count to be 8
int CurrentProjectileCount = 8;
//Function to decrease the current projectile count
public void DecreaseProjectileCount()
{
//Decrease the current projectile count by 1
CurrentProjectileCount--;
//Print out the current projectile count
ProjectileRef.GetComponent<TextMesh> ().text = CurrentProjecileCount.ToString ();
}
}
任何形式的帮助都是感激的!
我个人的做法:
ProjectileTracker tracker = GameObject.FindGameObjectWithTag("Projectile").GetComponent<ProjectileTracker>();
//If the spacebar is pressed
if (Input.GetKeyDown (KeyCode.Space) && tracker.ProjectileCount > 0)
{
//Instatiate a new projectile prefab 2 units above the Player sprite
Instantiate (Projectile, transform.position + transform.up * 2, Quaternion.identity);
//Find the game object with the tag "Projectile" and call the DecreaseProjectileCount() function from the ProjectileTracker script
tracker.ProjectileCount--;
}
…
using UnityEngine;
using System.Collections;
public class ProjectileTracker : MonoBehaviour {
//Variable to store the current projectile count
public GameObject ProjectileRef;
//Set the current projectile count to be 8
private int projectileCount = 8;
public int ProjectileCount
{
get { return projectileCount; }
set { SetProjectileCount(value); }
}
//Function to decrease the current projectile count
public void SetProjectileCount(int value)
{
projectileCount = value;
//Print out the current projectile count
ProjectileRef.GetComponent<TextMesh> ().text = value.ToString();
}
}