Commenting on Coding
- Keshav Batra
- Sep 23, 2021
- 7 min read
Updated: Sep 23, 2021
Jump Scare
public class JumpTrigger : MonoBehaviour
{
public AudioSource ScreamObject;
public GameObject Player;
public GameObject JumpCam;
public GameObject FlashIng;
public GameObject Zombie;
public bool once = true;
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<PlayerMovement>()&& once) //If the player collides with the jumptrigger
{
once = false;
ScreamObject.Play(); //Plays the jumpscare sound
JumpCam.SetActive(true); //Sets the zombie camera in front of the player
Player.SetActive(false); //Prevents the player from moving unecessarily while the jumpscare is happening
FlashIng.SetActive(true); //Creates an image in the players vision
if (Zombie)
{
Zombie.GetComponent<ZombieMovement>().activate = false; //Prevents the zombie from moving while doing a jumpscare
}
StartCoroutine(EndJump()); //Ends the jumpscare by calling the EndJump IEnumerator and goes to line 35
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
IEnumerator EndJump() //Ends the jumpscare
{
yield return new WaitForSeconds(2.03f); //Waits 2 seconds before ending the jumpscare
Player.SetActive(true); //Gets the player moving again
JumpCam.GetComponent<Camera>().enabled = false; //Disables the zombie camera
FlashIng.SetActive(false); //Disables the image in front of the player
if (Zombie)
{
print("Move"); //Prints the word in the console
Zombie.GetComponent<ZombieMovement>().activate = true; //Allows the zombie to move once the jumpscare is done
}
JumpCam.GetComponent<AudioListener>().enabled = false; //Disables the jumpscare audio
}
}
Zombie Movement
public class ZombieMovement : MonoBehaviour
{
public NavMeshAgent agent;
private Transform player;
public LayerMask whatIsGround, whatIsPlayer;
public float health;
public bool activate;
public bool IsDead;
public GameObject Zombie;
public bool ZombieSpawn = true;
//Patrolling
public Vector3 walkPoint;
bool walkPointSet;
public float walkPointRange;
public Animator AnimationController;
//Attacking
public float timeBetweenAttacks;
public bool alreadyAttacked;
public Animator AttackAnimation;
public Animator DeathAnimation;
//States
public float sightRange, AttackRange;
public bool playerInSightRange, playerInAttackRange;
private void Start()
{
if (activate) //If the zombie is activated
{
player = GameObject.Find("Player").transform; //Tracks down the player
}
}
private void OnEnable() //Plays the function whenever the zombie gets enabled
{
player = GameObject.Find("Player").transform; //Finds the player
}
private void Update()
{
if (activate && !IsDead) // Checking to see if the zombie is activated and is not dead
{
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer); //If the player is in sight of the zombie
playerInAttackRange = Physics.CheckSphere(transform.position, AttackRange, whatIsPlayer); //If the player is in attack range of the zombie
if (!playerInSightRange && !playerInAttackRange) Patrolling(); //If the player is not in attack range and not sight range of the zombie while patrolling
if (playerInSightRange && !playerInAttackRange) ChasePlayer(); //If the player is not in attack range and sight range of the zombie while chasing the player
if (playerInAttackRange && playerInSightRange) AttackPlayer(); //If the player is in attack range and sight range of the zombie while trying to attack the player
}
}
void Patrolling()
{
if (!walkPointSet) SearchWalkPoint(); //If the walkpoint is not set, them search for the walkpoint
//if (walkPointSet) SearchWalkPoint();
if (walkPointSet) //If the walkpoint is set
{
agent.SetDestination(walkPoint); //Set the destination for the zombies walkpoint
AnimationController.SetBool("IsRunning", true); //Enable the running animation for the zombie
AttackAnimation.SetBool("IsAttacking", false); //Disable the attack animation for the zombie
}
Vector3 distancetoWalkPoint = transform.position - walkPoint; //The zombies distance to walk point is equaled to the transform with the position minus the zombie movements walking distance
//Walkpoint reached
if (distancetoWalkPoint.magnitude < 1f) //If the distance to walkpoint with magnitude is less than 1
walkPointSet = false; //The zombie movements walkpoint will be disabled
}
private void SearchWalkPoint()
{
//Calculate random point in range
float randomZ = Random.Range(-walkPointRange, walkPointRange); //Random Z axis is equal to the random walkpoint range
float randomX = Random.Range(-walkPointRange, walkPointRange); //Random X axis is equal to the random walkpoint range
walkPoint = new Vector3(transform.position.x + randomX, transform.position.z + randomZ); //Walkpoint equals the location the zombie needs to go next
if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround)) //If the physics raycast detects the ground then its true
walkPointSet = true; //WalkpointSet is set to true
}
private void ChasePlayer() //Chases the player
{
agent.SetDestination(player.position); //Sets the zombie moving towards the players position
AnimationController.SetBool("IsRunning", true); //Enables the running animation
AttackAnimation.SetBool("IsAttacking", false); //Stops the attack animation
}
private void ResetAttack() //Resets the attack function
{
alreadyAttacked = false; //Disables already attacked
}
public void TakeDamage(int damage)
{
health -= damage; //Makes sure that the zombies health gets subtracted everytime they get shot
if (health <= 0 && !IsDead) //If the health of the zombie is less than or equal to 0 and is not dead
{
IsDead = true; //The Zombie is dead
agent.isStopped = true; //Stops the zombie movement
StartCoroutine(WaitForZombieDead()); //Waits for the zombies to be killed by calling the IEnumerator
}
}
IEnumerator WaitForZombieDead() //Waits for the zombie to be killed
{
DeathAnimation.SetBool("IsDead", true); //Plays the death animation of the zombie
PlayerManager.instance.currentZombiesInPlay -= 1; //Makes sure that the current number of zombies in play are precise
PlayerManager.instance.SpawnObject(); //Spawns the zombies
yield return new WaitForSeconds(2); //Waits 2 seconds before destroying the zombie
Destroy(gameObject); // Destroys the zombie
}
private void AttackPlayer() //Attacks the player
{
agent.SetDestination(transform.position); //Sets the current position of the zombie and has it stay there
Vector3 LookPosition = player.position; //Stores the players position
LookPosition.y = transform.position.y; //Look position on the Y axis is equal to the transform with the position on the Y axis
transform.LookAt(LookPosition); //Makes the zombie look at the player
if (!alreadyAttacked)
{
player.gameObject.GetComponent<PlayerMovement>().TakeDamage(10); //Has the player take 10 damage whenever they're hit
alreadyAttacked = true; //Sets already attacked to true once the player gets hit
Invoke(nameof(ResetAttack), timeBetweenAttacks); //Resets the zombie attacks
AnimationController.SetBool("IsRunning", false); //Disables the running animation
AttackAnimation.SetBool("IsAttacking", true); //Sets the animation to IsAttacking
}
}
}
Player Movement
public class PlayerMovement : MonoBehaviour
{
private CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public float HealthDamage;
private Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public int maxHealth=100;
public int CurrentHealth;
public HealthBar healthBar;
public GameObject GotHitScreen;
AudioSource Footsteps;
public AudioClip[] WalkingSound;
bool FootstepsAudio;
bool Walking;
Vector3 velocity;
bool isGrounded;
private void Start()
{
Footsteps = GetComponent<AudioSource>(); //Stores the audio source
controller = GetComponent<CharacterController>(); //Stores the character controller
groundCheck = GameObject.Find("GroundCheck").transform; //Finds the ground check, looks for its transform and stores its
CurrentHealth = maxHealth; //Current health is at its max at the beginning
healthBar.SetMaxHealth(maxHealth); //Set the health bar to max health
}
// Update is called once per frame
private void OnCollisionEnter(Collision collision) //If the zombie collides with the player
{
if (collision.gameObject.tag == "Zombie") //The player colliding with the zombie
{
gotHurt(); //Signals that the player got hurt
}
}
void gotHurt() //If the player gets hit, then the got hit screen will flash
{
var color = GotHitScreen.GetComponent<Image>().color; //Stores the color of the got hit screen
color.a = 0.5f; //Setting the transparency of the red screen to 50%
GotHitScreen.GetComponent<Image>().color = color; //Shows the red screen briefly
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); //Checks to see if the player is on the ground
if(isGrounded && velocity.y < 0) //If the player is grounded and the velocity is less than 0
{
velocity.y = -2f; //Keeps the player stable on the ground once it falls
}
float x = Input.GetAxis("Horizontal"); //Stores the left and right input values
float z = Input.GetAxis("Vertical"); //Stores the forward and backward values
Vector3 move = transform.right *x+transform.forward*z; //Stores the position the player would move
controller.Move(move * speed*Time.deltaTime); //Makes the player move
if (!Walking) //If the player is not walking
{
if (x != 0f || z != 0f) //If x or z are not equal to 0
{
Walking = true; //Walking is enabled
if (!FootstepsAudio) //If footsteps audio is not valid
{
FootstepsAudio = true; //Enables the footsteps audio
InvokeRepeating("playFootstepsAudio", 0f, 0.5f); //Repeats the footsteps audio
}
}
}
else if (x == 0 && z == 0) //If x and z are equal to zero
{
Walking = false; //Walking is disabled
FootstepsAudio = false; //Footsteps audio is disabled
CancelInvoke("playFootstepsAudio"); //Stop calling Footsteps audio
GetComponent<AudioSource>().Stop(); //Stop playing footsteps audio
}
if (Input.GetButtonDown("Jump")&& isGrounded) //If the space button is pressed and the player is on the ground
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity); //The height the player will jump
}
velocity.y += gravity * Time.deltaTime; //The player is falling
controller.Move(velocity * Time.deltaTime); //The player movement
if (GotHitScreen != null) //If the got hit screen is valid
{
if (GotHitScreen.GetComponent<Image>().color.a > 0) //If transparency is greater than 0
{
var color = GotHitScreen.GetComponent<Image>().color; //Stores the color in the variable
color.a -= 0.01f; //Color intensity
GotHitScreen.GetComponent<Image>().color = color; //Sets the color of the got hit screen
}
}
}
void playFootstepsAudio() //Plays the footsteps audio
{
GetComponent<AudioSource>().clip = WalkingSound[Random.Range(0, WalkingSound.Length)]; //Stores the footsteps audio
GetComponent<AudioSource>().Play(); //Plays the footsteps audio when the player moves
}
public void TakeDamage(int damage) //The player takes damage
{
//= sets a variable
CurrentHealth -= damage; //Subtracts the players health
healthBar.SetHealth(CurrentHealth); //Sets the health to its current state
gotHurt(); //Signals that the player got hurt
// Health=100-10=90
if (CurrentHealth <= 0) //If the players current health reaches 0
{
SceneManager.LoadScene("First Person Game"); //Reloads the scene when the player dies
SceneManager.LoadScene("Test_Map", LoadSceneMode.Additive); //Reloads the scene when the player dies
}
}
public void GainHealth(int hp) //Where the player gains health if it collects an object
{
if (CurrentHealth < maxHealth) //If current health is less than max health
{
CurrentHealth += hp; //Add to current health
healthBar.SetHealth(CurrentHealth); //Set the current health to max
}
}
}
This was some code from Vives Game
public class CoopZone_S : MonoBehaviour
{
float rayCastRange = 5f;
bool playerColliding = false, triggerOnce = true, cornDetected = false;
GameObject player; //Player is the game object
private IEnumerator Start() //Starts the coop zone
{
yield return new WaitForSeconds(1f); //Wait 1 second
player = GameManager.instance.GetPlayer().gameObject; //Gets the player
}
private void OnTriggerEnter(Collider other) //The player collides with the coop
{
if (other.GetComponent<Player_S>() && triggerOnce) //If the player collides with the coop one time
{
triggerOnce = false;
playerColliding = true; //The player collides with the coop
if (!cornDetected) //If Corn is not detected
StartCoroutine(DetectCornParticle()); //Waits for the corn to be detected
}
}
private void OnTriggerExit(Collider other)
{
if (other.GetComponent<Player_S>()) //If the player exits the coup
{
triggerOnce = true;
playerColliding = false; //Player Colliding is disabled
}
}
IEnumerator DetectCornParticle() //Detects the corn particle
{
do
{
if (playerColliding && player) //If the player collides with the coup zone
{
Vector3 dropDirection = player.transform.position + (player.transform.forward * 1f); //The corns drop direction would be forward in front of the player and is stored in the drop direction
RaycastHit hit;
if (Physics.Raycast(dropDirection, -transform.up, out hit, rayCastRange)) //If the physics raycast is thrown downwards
{
if (hit.transform == transform && !cornDetected && GameManager.instance.GetPlayer().ThrewCorn()) //If the coup zone recieved the corn
{
cornDetected = true; //Corn detected is true
}
}
}
else //If the player doesn't collide with the coup zone
break; //Breaking the loop
yield return null; //Corn is not valid
} while (!cornDetected); //Repeats every time the corn is not detected
}
}
Comments