Well I'm working with ball game , Every thing is working fine , Now i want to add Sound when the two balls collide each other .
I tried the following code but the sound is being repeated.I want it will play only once when collision start & not at collision maintained.
In onCreateResources:
SoundFactory.setAssetBasePath("sfx/");
try {
mSound = SoundFactory.createSoundFromAsset(getSoundManager(), this, "coll2.m4a");
} catch (IOException e) {
e.printStackTrace();
}
And added below code in onAccelerationChanged(AccelerationData pAccelerationData)
if (face.collidesWith(face1) || face.collidesWith(face2))
{
mSound.play();
}
You could have a boolean to check if the sprites have already collided. The code would look something like this.-
if (face.collidesWith(face1) || face.collidesWith(face2)) {
if (!colliding) {
colliding = true;
mSound.play();
}
} else {
colliding = false;
}
Related
I am trying to convert my PC game code in unity to android and I am stuck on the controls change. Please help!
This is the code:
Getting the state of rocket.
enum State { Dying, Alive, Transcending }
State state = State.Alive;
// Update is called once per frame
void Update()
{
if (state == State.Alive)
{
RespondToThrustInput();
RespondToRotateInput();
}
}
When the rocket collides with anything it checks whether it's friendly or not before changing its state from alive to dead.
private void OnCollisionEnter(Collision collision)
{
if (state != State.Alive) { return; }
switch (collision.gameObject.tag)
{
case "Friendly":
break;
case "Finish":
state = State.Transcending;
audioSource.Stop();
audioSource.PlayOneShot(finishgame);
finishgameParticles.Play();
Invoke("LoadNextScene", levelloaddelay);
break;
default:
state = State.Dying;
audioSource.Stop();
audioSource.PlayOneShot(death);
deathParticles.Play();
Invoke("LoadFirstScene", levelloaddelay);
break;
}
}
private void LoadFirstScene()
{
SceneManager.LoadScene(9);
}
Loading next scene using build index.
private void LoadNextScene()
{
if (nextscenetoload > 7)
{
nextscenetoload = 0;
}
SceneManager.LoadScene(nextscenetoload);
}
Space for ignition or force and audio sources for playing sound effects.
private void RespondToThrustInput()
{
if (Input.GetKey(KeyCode.Space))
{
ApplyThrust();
}
else
{
audioSource.Stop();
mainengineParticles.Stop();
}
}
Apply thrust is the method I wrote with the logic of the rocket thrust.
private void ApplyThrust()
{
rigidbody.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime);
if (!audioSource.isPlaying)
audioSource.PlayOneShot(mainengine);
mainengineParticles.Play();
}
Rotation of the rocket or Left and right. Here I am trying to rotate the rocket using the A and D keys
void RespondToRotateInput()
{
float rotationThisFrame = rcsThrust * Time.deltaTime;
if (Input.GetKey(KeyCode.A))
{
rigidbody.freezeRotation = true;
transform.Rotate(Vector3.forward * rotationThisFrame);
rigidbody.freezeRotation = false;
}
else if (Input.GetKey(KeyCode.D))
{
rigidbody.freezeRotation = true;
transform.Rotate(-Vector3.forward * rotationThisFrame);
rigidbody.freezeRotation = false;
}
}
For PC games there is a keyboard to use to control, but for the android there are touches, you have to verify if there is a touch on the screen, like this:
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
//do something
}
also you need more work to determine where the touch is located and do you customizations... or in case you're not interested about this input handling, you can use some assets from Unity Assets Store to cover this part for you.
check this link for more information about touch control in Unity documentation:
https://docs.unity3d.com/ScriptReference/Input.GetTouch.html
I have a button for which i'd like to signify "attacking". I'm programming for android.
Basically i'd like to run this script, upon the touch of the attack button. Instead of using the F key to stop the code from rapidly repeating, i'm trying to figure out how to run an if statement for "if button is touched & !isAttacking" then go into the method.
if (Input.GetKeyDown(KeyCode.F) && !isAttacking)
{
isAttacking = true;
attackTimer = attackCD;
Debug.Log("F Pressed");
attackTrigger.enabled = true;
}
if (isAttacking)
{
if (attackTimer > 0)
{
attackTimer -= Time.deltaTime;
}
else
{
isAttacking = false;
attackTrigger.enabled = false;
}
}
I'm using Unity 5!
I am developing a block game. i have two moving blocks in vertical direction. one of the block is also moving horizontally (like auto moving car in ROAD FIGHTER). i am checking the block interaction by Intersector.overlaps but when my block goes out of window (i.e. position becomes less than 0) ,my code of overlaps not working .
if(Intersector.overlaps(block1.getBoundingRectangle(), block2.getBoundingRectangle())){
// do not update values
}else{
// update the values of block1 and block 2
}
public static int[] value={138,195,248,303};
public static boolean[] valueHolder={true,false,false,true};
public void update(float delta) {
velocity.set(0, backgroun.velocity.y-scrollSpeed);
position.add(velocity.cpy().scl(delta));
if(position.y>850){
isScrollableTop=true;
}
selfMove(delta);
if(position.y<-150){
position.y=-150;
}
carBoundingRectangle.setX(position.x);
carBoundingRectangle.setY(position.y);
}
private void changeArray() {
if(position.x>=138 && position.x<167){
if(!GameConstants.valueHolder[0]){
GameConstants.valueHolder[blockNumber]=false;
GameConstants.valueHolder[0]=true;
blockNumber=0;
}
}else if(position.x>=167 && position.x<222 ){
if(!GameConstants.valueHolder[1]){
GameConstants.valueHolder[blockNumber]=false;
GameConstants.valueHolder[1]=true;
blockNumber=1;
}
}else if(position.x>=222 && position.x<275){
if(!GameConstants.valueHolder[2]){
GameConstants.valueHolder[blockNumber]=false;
GameConstants.valueHolder[2]=true;
blockNumber=2;
}
}else if(position.x>=275 ){
if(!GameConstants.valueHolder[3]){
GameConstants.valueHolder[blockNumber]=false;
GameConstants.valueHolder[3]=true;
blockNumber=3;
}
}
}
Thanks in advance
I have a Sound loaded in the onCreateResources method.
try {
shield = MusicFactory.createMusicFromAsset(this.getMusicManager(), this, "shield.ogg");
} catch (IOException e) {
e.printStackTrace();
}
shield.setVolume(1.0f);
shield.setLooping(true);
When i play the sound the first time it works fine, however, the following times i play it is seems random if it works or not.
i use shield.play(); to play the sound and shield.stop(); to stop it again.
When it doesnt work i get the following in the log.
AudioFlinger could not create track, status: -12
Error creating AudioTrack
Using Music when you play background music, it will be control long play, repeat..
Using Sound when you play a short audio, example when press button, or shoot..etc
Here the my same code using both of them:
public static void controlBgAudio(boolean play, boolean repeat) {
Music ms = ResourceManager.getInstance().audioBgMusic;
if (play) {
if (ms.isReleased()) {
ms.resume();
} else {
ms.play();
}
} else {
if (ms.isPlaying()) {
ms.pause();
} else {
ms.stop();
}
}
if (repeat) {
ms.setLooping(true);
} else {
ms.setLooping(false);
}
}
public static void controlShootAudio(boolean play, boolean repeat) {
Sound ms = ResourceManager.getInstance().audioShoot;
if (play) {
if (ms.isReleased()) {
ms.resume();
} else {
ms.play();
}
} else {
if (ms.isLoaded()) {
ms.pause();
} else {
ms.stop();
}
}
if (repeat) {
ms.setLooping(true);
} else {
ms.setLooping(false);
}
}
You don't use the MusicFactory for sound effects. It is strictly for music.
You are supposed to use the SoundFactory.
Here is an example:
Sound sound = SoundFactory.createSoundFromAsset(getSoundManager(), this, "sound.wav");
I know it is possible as the camera app that comes with my droid phone does it, but for the life of me, I don't seem to be able to switch cameras on the fly either for video or a standard camera (which leads me to suspect I'm not doing it right!)
Currently, I have an event for the button
btnSwitchCamera.Click += new EventHandler(btnSwitchCamera_Click);
prior to that, I check for the number of cameras - if there is only one camera, the event is not enabled.
The switch code looks like this
private void btnSwitchCamera_Click(object s, EventArgs e)
{
if (isBackCamera == false)
{
try
{
RunOnUiThread(delegate
{
camera.Release();
camera = Android.Hardware.Camera.Open(1);
});
}
catch (Java.Lang.RuntimeException)
{
alertMsg(context, Application.Context.Resources.GetString(Resource.String.videoErrorTitle),
Application.Context.Resources.GetString(Resource.String.videoFailToConnect));
return;
}
isBackCamera = true;
}
else
{
try
{
RunOnUiThread(delegate
{
camera.Release();
camera = Android.Hardware.Camera.Open(0);
});
}
catch (Java.Lang.RuntimeException)
{
alertMsg(context, Application.Context.Resources.GetString(Resource.String.videoErrorTitle),
Application.Context.Resources.GetString(Resource.String.videoFailToConnect));
return;
}
isBackCamera = false;
}
}
If I click the button, the app dies claiming that I cannot connect to the service.
The video record code is nothing special - it's a bog standard set the surface, do the holder, and start/stop recording.
Am I doing this right? From the docs, I need to release the camera then open the camera with the appropriate camera number (Android.Hardware.Camera.NumberOfCameras - 1)
The manifest is correctly set.
Thanks
Paul