Introduction:
In this sixth installment of our Beat Saber game development series, we're diving into the heart of lightsaber mechanics. Today, we'll explore how to dynamically control the activation and deactivation of our lightsaber blade, complete with the immersive addition of sound effects. Get ready to harness the Force as we craft the code for turning on and off the lightsaber blade.
Code Explanation:
Let's break down the key components of the LightSaberController
script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightSaberController : MonoBehaviour
{
public AudioClip bladeOnSound;
public AudioClip bladeOffSound;
public enum Hand { LEFT, RIGHT };
public Hand hand = Hand.RIGHT;
private AudioSource audioSource;
private GameObject blade;
private bool isBladeOn = false;
// Start is called before the first frame update
void Start()
{
blade = transform.Find("blade").gameObject;
blade.SetActive(false);
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
// Input check for activating the lightsaber blade
if ((hand == Hand.RIGHT && OVRInput.GetDown(OVRInput.RawButton.A)) ||
(hand == Hand.LEFT && OVRInput.GetDown(OVRInput.RawButton.X)) ||
Input.GetKeyDown(KeyCode.Space))
{
if (isBladeOn)
{
TurnBladeOff();
}
else
{
TurnBladeOn();
}
}
}
void TurnBladeOn()
{
// Activate the lightsaber blade and play the activation sound
blade.SetActive(true);
isBladeOn = true;
audioSource.clip = bladeOnSound;
audioSource.Play();
}
void TurnBladeOff()
{
// Deactivate the lightsaber blade and play the deactivation sound
blade.SetActive(false);
isBladeOn = false;
audioSource.clip = bladeOffSound;
audioSource.Play();
}
}
Detailed Explanation:
Audio Clips:
We start by defining two public
AudioClip
variables,bladeOnSound
andbladeOffSound
, to store the sound effects for turning the lightsaber blade on and off.
Hand Enumeration:
- The
Hand
enum allows us to specify whether the lightsaber is in the left or right hand.
- The
Variables Initialization:
- We initialize the
audioSource
to handle audio playback and locate the lightsaber blade GameObject within the script's hierarchy during theStart
method.
- We initialize the
Input Handling:
- In the
Update
method, we check for input events that trigger lightsaber blade activation. This includes Oculus VR controller buttons (A for right hand, X for left hand) and the space key.
- In the
Turning On/Off the Blade:
- The
TurnBladeOn
andTurnBladeOff
methods handle the activation and deactivation of the lightsaber blade, respectively. They also set the appropriate audio clip and play the corresponding sound effects.
- The
Conclusion:
With this script, you've successfully implemented the mechanics for turning on and off the lightsaber blade, enhancing the player's control over this iconic weapon. In the next blog, we'll take it a step further by adding dynamic sound effects and animations to elevate the lightsaber experience.
Happy Coding :)