Play sound when other object(ball) hit cube - audio

using UnityEngine;
using System.Collections;
public class audio : MonoBehaviour
{
public AudioClip hitsound;
void Update ()
{
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Ball")
{
GetComponent.<AudioSource>().PlayOneShot (hitsound);
}
}
}
I assign .mp3 file to inspector, and also, I added Audio Source component but I can't hear hit sound. Cubes which need to be destroyed is moving during game. I added that script and audio source component on parts which are not moving and when ball hit that non-moving parts, sound is playing (every time).
I hope that someone can help me with this.
Thanks and kind regards

YOU HAVE A TYPO
GetComponent.<
SHOULD BE
GetComponent<
Doesn't the . after GetComponent give you an error?
Anyway, make sure your colliders are set as triggers (checkbox on component).
Also I think Unity recommend using CompareTag() instead of ==.
It's worth putting a Debug.Log into the OnTriggerEnter2D to see if that is even firing.
Finally, make sure your colliders are the 2D versions, not just the regular colliders.

Related

Main Camera Referenced script is missing

I know, there is always a lot of questions about this error BUT I didn't succeed to fix it with the previous answers...
So, please, let me explain.
I'm working with the Hololens tech. Recently, I have updated from HoloToolKit to MRTK V2 (new SDK provided by Microsoft and the community). My app worked with HoloToolKit, Unity and 2017.4. I updated for MRTKv2 and 2019.2 (recommended).
I have some scripts that use the camera position. In my previous app, Camera was BiCamera (GameObject), child of Basic (GameObject). And my BiCamera was tagged as MainCamera. Right now, my camera was Main Camera (with a space between the 2 words), tagged MainCamera, child of MixedRealityPlayspace. This camera is provided by the MRTKv2. I can't change the settings.
So, when I'm in a Play mode I have this message in yellow :
The referenced script on this Behaviour (Game Object 'Main Camera') is missing!
And when I move my Main Camera in order to simulate a walk of the user (Hololens = augmented reality), I have this message in red :
NullReferenceException: Object reference not set to an instance of an object
TextSpeedUI.Update () (at Assets/Scripts/TextSpeedUI.cs:23)
I think the second message is linked to the first... My script TextSpeedUI needs the camera.transform to calculate walking speed (in fact not directly, he finds the public variable from another GameObject, but this GameObject requires Camera.transform).
An other option is linked with the GameObject Main Camera provided by MRTK because when I select this GameObject I have a missing script. A message says that I have to fix compile errors... But perhaps it's a consequence not the origin... I'm lost.
TextSpeedUI.cs 23
if (sd.isActiveAndEnabled && sd.Steps.Count > 4)
{
xzSpeed = (sd.Steps[sd.Steps.Count - 1].localMinPosition - sd.Steps[sd.Steps.Count - 4].localMinPosition) / ((sd.Steps[sd.Steps.Count - 1].t - sd.Steps[sd.Steps.Count - 4].t));
txt.text = (xzSpeed.magnitude * 3.6).ToString("0.##"); // speed in km/h
}
sd comes from public StepDetector sd; which is at the beginning of my script TextSpeedUI.cs
And my script StepDetector.cs calls public DataManager dm;
In my DataManager.cs script, I call at the beginning :
public Camera Cam { get; private set; }
And in void Start :
Cam = Camera.main;
Thanks a lot
I've solved by myself (just remove the component). It seems that it doesn't have consequence on my scene...

Object Collision Issue - Weird Behaviour - Unity

I wondering if someone could give me a hand with this problem I'm having with objects and collisions in Unity.
I have a sphere object being controlled by the users phone's accelerometer. The sphere moves around fine but once it hits a wall the sphere starts acting weird. It pulls in the direction of the wall it collided with, starts bouncing, and just overall not responsive anymore to the movement of the phone.
Any idea as to why this could be happening?
Here is the script used to control the player's sphere.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
void Update() {
Vector3 dir = Vector3.zero;
dir.x = Input.acceleration.x;
dir.z = Input.acceleration.y;
if (dir.sqrMagnitude > 1)
dir.Normalize();
dir *= Time.deltaTime;
transform.Translate(dir * speed);
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Pickup") {
other.gameObject.SetActive(false);
}
}
}
That happens because your object has a 'Rigidbody' component, and, I suppose, it's not a kinetic rigidbody. Basically, it behaves just like it should: a real physical object will not pass through another object, that is the most basic behaviour of a physics engine. However, since you don't operate with the physics-based object using forces, but manually change it's position, you break a level of abstraction. In result, you move the object inside the wall, and now it can't get out.
Use ApplyForce method instead. If you want to pull or push object (instead of just move, which contradicts the fact that these objects are managed by physics) in a certain direction every frame, you should use ForceMode.Acceleration (or ForceMode.Force, if you want the effect to depend on the mass) every physics frame, which means that you have to use FixedUpdate method instead of Update.

Muting 'Sound' instead of 'Music' in libgdx

I'm developing a simple game using eclipse and libgdx.
Currently, I'm using 'Music' instead of 'Sound' for sound effects for my game.
I made a button for muting all of the sound fx but having a problem when it comes to 'sound' instead of music.
Here's my current code:
public static Music jump;
public static void load() {
jump = Gdx.audio.newMusic(Gdx.files.internal("data/jump.wav"));
}
public static void muteFX() {
lesgo.setVolume(0);
public static void normalizeFX() {
jump.setVolume(1f);
//'muteFX' and 'normalizeFX' to be called on different class
I wanted to change it to 'Sound' (the reason is I wanted it to be more responsive on fast clicks,) So it could be like this:
public static Sound jump;
public static void load() {
jump = Gdx.audio.newSound(Gdx.files.internal("data/jump.wav"));
}
/* here comes my problem, didn't know how to set mute and normal
volume for the jump sound. I know there is also a set volume method
to 'Sound' but really confused on the terms (long soundID, float volume)
Can someone make this clear to me on how to implement the long and soundID?
*/
I'm really new to libgdx, as well as in java. I researched many forums regarding this and still can't find a more clearer explanation.
Any help will be greatly appreciated.
Thanks a lot in advance! =)
A quick suggestion would be to use a global variable for sound
public static VOLUME = 1.0f;
The sound api allows you to play a sound at a certain volume, so what you could do is have all the sounds in your game play at that global value when needed.
jump.play(VOLUME);
this way, all your switch will do is change the float value of volume.
public static void muteFX(){
VOLUME = 0.0f;
}
public static void normalizeFX(){
VOLUME = 1.0f;
}
It would be in your best interest to not use the Music class for sound effects due to memory constraints.
I hope this helps
In the documentation it states that the id is returned when play() or loop() methods succeed. This might not be convenient depending what are you trying to achieve. Basicly you can get the id and use it with something similar to this:
long id = sound.play(1.0f); // play new sound and keep handle for further manipulation
sound.stop(id); // stops the sound instance immediately
sound.setPitch(id, 2); // increases the pitch to 2x the original pitch
When I wanted to have a button Volume OFF and Volume ON I had a global variable which I would check before I play the sound somethign similar to this:
In my main Game Class:
public static boolean soundEnabled;
Whenever I wanted to play sound.
if (MyMainClass.soundEnabled)
sound.play();
In case you want any other control of the sound then inevetably you need to get the sound's id.

hover effect that make some object to change or move, using (maybe) processing.js?

I spent whole night to figure it out how does hover effect on this site http://goo.gl/WXlGT work. But i still cant get it. At first i thought that its made in flash, than i thought its html5 but finally i found out its using processing.js (i can be wrong). I checked their sites but i have no idea how to do it.
All what i want to know is how to make hover effect of one object (for example menu) that will make some other object (for example logo) to change or move. Perfect example of what im looking for is here: http://goo.gl/I777F .
Any help or hints to some manual on web would be very appreciated. Thank you!
This is a general object oriented programming question, with a general object oriented answer. In generic Processing code:
ArrayList<Drawable> things;
...
void somePlacementFunction() {
...
things.add(new Drawable(<some parameters>));
...
}
...
void draw() {
for(Drawable things: things) {
thing.draw();
}
}
...
void mouseMoved() {
for(Drawable thing: things) {
if(thing.over(mouseX, mouseY)) {
Drawable differentThing = getOtherThing(...);
differentThing.changeSomePropertyThatAffectsHowItGetsDrawn();
}
}
}
In this specific case, the Processing code is http://labfiftyfive.com/res/mathsbaby2.pde and the on-page JS triggers it as http://labfiftyfive.com/js/main.js line 162 and on.

j2me screen flicker when switching between canvases

I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects.
For example, the game menu is a Canvas object, and the actual game is a Canvas object too.
I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas.
Is there anyway to avoid this?
I would say, that using multiple canvases is generally bad design. On some phones it will even crash. The best way would really be using one canvas with tracking state of the application. And then in paint method you would have
protected void paint(final Graphics g) {
if(menu) {
paintMenu(g);
} else if (game) {
paintGame(g);
}
}
There are better ways to handle application state with screen objects, that would make the design cleaner, but I think you got the idea :)
/JaanusSiim
Do you use double buffering? If the device itself does not support double buffering you should define a off screen buffer (Image) and paint to it first and then paint the end result to the real screen. Do this for each of your canvases. Here is an example:
public class MyScreen extends Canvas {
private Image osb;
private Graphics osg;
//...
public MyScreen()
{
// if device is not double buffered
// use image as a offscreen buffer
if (!isDoubleBuffered())
{
osb = Image.createImage(screenWidth, screenHeight);
osg = osb.getGraphics();
osg.setFont(defaultFont);
}
}
protected void paint(Graphics graphics)
{
if (!isDoubleBuffered())
{
// do your painting on off screen buffer first
renderWorld(osg);
// once done paint it at image on the real screen
graphics.drawImage(osb, 0, 0, Tools.GRAPHICS_TOP_LEFT);
}
else
{
osg = graphics;
renderWorld(graphics);
}
}
}
A possible fix is by synchronising the switch using Display.callSerially(). The flicker is probably caused by the app attempting to draw to the screen while the switch of the Canvas is still ongoing. callSerially() is supposed to wait for the repaint to finish before attempting to call run() again.
But all this is entirely dependent on the phone since many devices do not implement callSerially(), never mind follow the implementation listed in the official documentation. The only devices I've known to work correctly with callSerially() were Siemens phones.
Another possible attempt would be to put a Thread.sleep() of something huge like 1000 ms, making sure that you've called your setCurrent() method beforehand. This way, the device might manage to make the change before the displayable attempts to draw.
The most likely problem is that it is a device issue and the guaranteed fix to the flicker is simple - use one Canvas. Probably not what you wanted to hear though. :)
It might be a good idea to use GameCanvas class if you are writing a game. It is much better for such purpose and when used properly it should solve your problem.
Hypothetically, using 1 canvas with a sate machine code for your application is a good idea. However the only device I have to test applications on (MOTO v3) crashes at resources loading time just because there's too much code/to be loaded in 1 GameCanvas ( haven't tried with Canvas ). It's as painful as it is real and atm I haven't found a solution to the problem.
If you're lucky to have a good number of devices to test on, it is worth having both approaches implemented and pretty much make versions of your game for each device.

Resources