Making my first game: changing a game’s music through ball collision

I made a simple game in Unity where you control a ball with the arrow keys, and try to hit the various red capsules in the field. At first, there’s background music playing from every single capsule, but as you hit more and more capsules, the music becomes more and more jumbled and disordered. This is because I used a simple function that makes the pitch of the music coming from that particular capsule random if you hit it. So, after you hit a bunch of capsules, it’s a jingly chaos, and gradually the music dies away and you’re left alone with the sound of the breeze.

Screenshot of the game:

Screen Shot 2017-07-20 at 11.11.47 PM

Code that activates when the ball collides with an object


using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class basheycollide : MonoBehaviour {
// add audio whenever the box is bashed into AudioSource cataudio;

void Start () {
cataudio = GetComponent (); } // Update is called once per frame void Update () { }

void OnCollisionEnter (Collision collisionthing) {
// box collider is an invisible surface that surrounds the cube  // function called whenever the box gets hit
// we can debug by doing this: Debug.Log("hey! I got a collision! yay :)");
// make the pitch random every time the object is bashed into cataudio.pitch = Random.Range (0.5f, 2.0f);
cataudio.Play ();}
}

Code to rotate the capsules


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class basheyrotate : MonoBehaviour {

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime);

}
}

 


Code to move the ball


using System.Collections;
using System.Collections.Generic;
using UnityEngine;]
public class rolleyballmover : MonoBehaviour {

// variable declarations
private Rigidbody rb;
public float speed;

// Use this for initialization
void Start () {

// get the RigidBody component for our sphere
rb = GetComponent();

}

// Update is called once per frame
void FixedUpdate () {

// called every time class starts
// fixed-update: happens before all the rendering for frames happens
// late-update: happens after the rendering happens

float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");

// force vector, ball is not allowed to jump
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed); // multiply by a value to make the ball move faster

}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s