嘿,我正在制作一個僵尸游戲,我希望每次僵尸與我的玩家碰撞時,只要它們碰撞它就應該每 2 秒造成一次傷害,它應該繼續。雖然不碰撞它應該停止。我所做的是下面這段代碼,它的問題是當我與僵尸相撞時,它會造成一次傷害并停止我需要再次與它相撞才能造成傷害 任何人都可以幫助僵尸造成傷害,只要他們正在碰撞,應該每 2 秒造成一次傷害,感謝您的幫助 :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public float Health = 100f;
public bool gameOver;
private Animator playerAnim;
float timeColliding;
// Start is called before the first frame update
private void Start()
{
playerAnim = GetComponent<Animator>();
}
private void Update()
{
if (Health <= 0)
{
playerAnim.SetBool("PlayerDeath", true);
gameOver = true;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
Debug.Log("Enemy started colliding with player.");
this.Health -= 10;
}
}
}
uj5u.com熱心網友回復:
我不擅長團結,但我認為這樣的事情會奏效。將所有代碼放在我的代碼中的 while 回圈中,以便在您的代碼中運行以檢測碰撞。而地方isEven在該函式之外。您可以在 c# 編譯器中測驗我的代碼。例如,如果您將//reduce health替換為Console.WriteLine("reduced"); 此代碼將每 2 秒減少列印一次
public class Program
{
public static void Main()
{
bool isEven = false;
while(true){
var timeSpan = DateTime.Now;
if(timeSpan.Second %2 == 0){
if(isEven == false){
//reduce health here
}
isEven = true;
}
else{
isEven = false;
}
}
}
}
在您的代碼中,它將如下所示:
public class PlayerHealth : MonoBehaviour
{
bool isEven = false;
public float Health = 100f;
public bool gameOver;
private Animator playerAnim;
float timeColliding;
// Start is called before the first frame update
private void Start()
{
playerAnim = GetComponent<Animator>();
}
private void Update()
{
if (Health <= 0)
{
playerAnim.SetBool("PlayerDeath", true);
gameOver = true;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
Debug.Log("Enemy started colliding with player.");
var timeSpan = DateTime.Now;
if(timeSpan.Second %2 == 0){
if(isEven == false){
//reduce health here
this.Health -= 10;
}
isEven = true;
}
else{
isEven = false;
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/316211.html
