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.
Related
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.
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.
From my few years of experience programming in graphics, one thing that I have learned is that you should never pass in a reference to a graphics context to an object and operate on it for the duration of the program (JOGL explicitly states this). A context can be invalidated when something such as the graphics device (GPU) is reset, turned off, or some other weird thing happens.
I have recently delved back into programming in XNA 4.0, and one of my projects involves objects needing to know about the size of the window/viewport, when the window is resized, and when dynamic buffers have lost their content (requiring the buffers to be rebuilt on a possibly invalidated GraphicsDevice). Instead of passing in the GraphicsDevice and GameWindow to numerous methods in the update phase or for Disposal, I have opted to pass them into constructors. For example:
public Camera(GameWindow w, GraphicsDeviceManager m) {
// ... Yada-yada matrices
gdm = m;
window = w;
window.ClientSizeChanged += OnWindowResize;
}
public void Dispose() {
window.ClientSizeChanged -= OnWindowResize;
window = null;
gdm = null;
}
// Control Logic ...
public void OnWindowResize(object Sender, EventArgs args) {
Vector2 s = new Vector2(gdm.GraphicsDevice.Viewport.TitleSafeArea.Width, gdm.GraphicsDevice.Viewport.TitleSafeArea.Height);
// Recalculate Projection ...
}
Is it safe to do something like this, or is something happening in the background that I need to be aware of?
I solved this problem in my current game project by running the game as a singleton, which makes it available in a static context within the namespace. Game.Instance.graphicsDevice will always point to the current graphics device object, even if the context has changed. XNA raises various events when the context is invalidated/changed/reset/etc., and you can reload/re-render things and resize buffers as needed by hooking in to these events.
Alternatively, you could pass GraphicsDevice with the ref keyword, which might be a quick, drop-in fix by simply being the same reference as the original caller, assuming that caller that instantiated your objects either has the original reference object or had the GraphicsDevice passed to it with ref as well.
In my ANDROID application, I am trying to develop an interactive image. The image is made of several interconnected nodes. I would like to tap on two different nodes to get the shortest path between them. When the nodes are tapped, I want to draw an overlay on top of the image which indicates the shortest path between the tapped nodes. In addition to this, I would want to implement the animation of the path from source node to intermediate nodes and finally to the destination node.
I was trying to implement this in Surface View.
Any suggestions on how to get started with this would be really helpful. Any tutorials, sample code which I can use as a guidance would be great.
You can start by creating your own surfaceview class that displays an image.
Make sure you implement SurfaceHolder.Callback in your surfaceview class.
public class MySurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mthread.setRunning(false);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
You can use a thread to call draw methods and render the image. Make sure to use Canvas locks while implementing Threads.
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.