I need help with adding sound off/on button to my game. In global variable lua file, I have the following:
local sounds = {}
sounds["select"] = audio.loadSound("sounds/select.mp3")
sounds["score"] = audio.loadSound("sounds/score.mp3")
G.playSound = function(name)
if sounds[name] ~= nil then
audio.play(sounds[name])
end
end
In games.lua file, I call the function as:
utils.playSound("score")
I have a soundon.png and soundoff.png files both in a sprite sheet (not sure if that is a good idea), all I am trying to implement is when you click the sound button, all sounds stops and it displays the soundoff image, vice versa.
Thanks
I personally wouldn't use a sprite sheet. Just load both images and toggle their "isVisible" field. Then toggle a variable which would stop your sounds. Try something like this.
myGlobalSoundToggle = true
local image = display.newImage("soundon.png")
local image2 = display.newImage("soundoff.png")
image2.isVisible = false
local function onTap( self, event )
image.isVisible = ~image.isVisible
image2.isVisible = ~image2.isVisible
myGlobalSoundToggle = image.isVisible
return true
end
image:addEventListener( "tap", onTap )
Now that we have our buttons working, we need to toggle the sound on and off.
local sounds = {}
sounds["select"] = audio.loadSound("sounds/select.mp3")
sounds["score"] = audio.loadSound("sounds/score.mp3")
G.playSound = function(name)
if (sounds[name] ~= nil) and (myGlobalSoundToggle) then
audio.play(sounds[name])
end
end
Related
I have displayed a Line chart using fl_chart ^0.10.1 (Tested on Flutter ver 52.2.1 & 53.0.1).
I am updating the FlSpots from a csv file.
I am trying to get the index or Spot object if I touch somewhere in the plot.
But I am getting an empty list from the touchResponse if I touch (both tap or long-press) somewhere.
But I am getting the value in the plot itself. I am assuming it's there because of the built-in touch handler.
The code I am trying it:
lineTouchData: LineTouchData(
touchCallback: (LineTouchResponse touchResponse) {
if (touchResponse.touchInput is FlPanEnd ||
touchResponse.touchInput is FlLongPressEnd) {
var spots = touchResponse.lineBarSpots;
setState(() {
var lengthList = spots.length;
print(
'touched spot---> ${spots.toString()},,,len--->$lengthList');
});
} else {
print('wait');
}
}),
My end goal is to use and pass the touched index to open a new screen/widget.
touchCallback: (LineTouchResponse? lineTouch) {
final value = lineTouch.lineBarSpots![0].x;
// set state...
});
It's in the demo by fl_chart in github.
https://github.com/imaNNeoFighT/fl_chart/blob/master/example/lib/line_chart/samples/line_chart_sample3.dart
I am currently working on an android app that allow user to rotate the image then save it. I am able to save the image but when I check it, it doesn't rotate. Would appreciate if someone can point me to a right direction.
Here is my code:
_rotateLeft.addEventListener('click', function(e){
_rotationDegree = _rotationDegree - 90;
var t = Ti.UI.create2DMatrix();
//t.rotate(90);
//imageContainer.transform = t;
imageContainer.animate({
transform: t.rotate(_rotationDegree)
});
});
_saveButton.addEventListener('click', function(){
var imgSave = imageView.toImage();
var moment = require('alloy/moment');
var directory = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, 'images/test');
!directory.exists() && directory.createDirectory();
var fileName = String.format('rotate_%s.jpg', moment().format('YYYY-MM-DD-HH-mm'));
var file = Ti.Filesystem.getFile(directory.resolve(), fileName);
var fileNativePath = file.nativePath;
// Write media to file
//file.write(newBlob);
file.write(imgSave);
Ti.API.info('New Save File : ' + JSON.stringify(file));
imageView.setImage(file);
});
Here is my view:
<View id="imageContainer">
<!--<View id="imageUploadedView"></View>-->
<ImageView id="imageView"></ImageView>
</View>
There are 2 things I found odd in your code:
1 - You are rotating imageContainer and then you are capturing imageView.toImage(); which I think is the cause of issue because:
Rotating container view rotates the child elements also, and capturing a child.toImage(); will return you the UI of that child irrespective of the rotation (though I am not 100% sure because I would prefer below step to do this task).
So to make to properly work, rotate imageView and use imageContainer.toImage(); so that child view is rotated and parent view can save its rotated state.
2 - Inside _saveButton click event, use this line:
imageView.setImage(file.read()); because you were not reading the blob data of the file in your code.
You need to declare the transform first then apply the transform to the view before saving.
_rotateLeft.addEventListener('click', function(e){
var rotateTransform = Ti.UI.create2DMatrix({
rotate: 45
});
imageContainer.transform = rotateTransform;
}
Reference: http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.2DMatrix
I am building a Cordova app for Android. I have to parse a JSON that consists of posts. Each post has text (title, description, category etc.) and images (an array of images - can be one or more). My aim is to store the JSON data for offline use (save to SQLlite database). Right now the example code below works, but the sequence is not how I expected to be:
request JSON (ok)
Wait for all promises (ok)
Parse JSON (finishes before all the images are downloaded)
Store to database the information but the images still downloading (in background thread - no harm for the UI).
What I would like to have is to store to database, when all the images have been downloaded. I' ve tried many things such as replacing the second for-loop with a recursive function (to handle the async function as stated here) and many other similar approaches but I believe that the problem starts from the 1st for loop which doesn't wait for the checkCache to finish. What do you think? How can I overcome this issue? If you need any further explanation just ask me.
My setup is:
Cordova 4.0.0, Angular 1.3.1 and ImgCache 1.0
My approach is:
1st. Request JSON:
promise1 = $http({method: 'GET', url: baseURL + options1};
promise2 = $http({method: 'GET', url: baseURL + options2};
//...
2nd. Wait for all promises
return $q.all([promise1,promise2,...]).then(function(data){
var promise1size = data[0].data.posts_number;//posts.length;
parseJSON(data[0],promise1size,'category1');
var promise2size = data[1].data.posts_number;//posts.length;
parseJSON(data[1],promise1size,'category2');
//similar for the rest promises
});
3rd. Parse JSON
function parseJSON(respdata,size,category){
console.log("Parsing "+size+" "+category);
for(i=0;i<size;i++){
var item = {};
item ["id"] = respdata.data.object[i].id;
item ["title"] = respdata.data.object[i].title;
item ["description"] = respdata.data.object[i].description;
var jsarray = respdata.data.object[i].categories;
item ["category"] = jsarray[0].title;
item ["catid"] = jsarray[0].id;
//Other JSON keys here similar as above
//Here it starts...
var jsattachement = respdata.data.object[i].attachments;
var atsize = jsattachement.length;
if(atsize>0){
var images=[];
for(j=0;j<atsize;j++){
(function(j){checkCache(jsattachement[j].url)}(j));//here is the problem
multimedia.push({title:item["title"], src:ImgCache.returnCachedURL(jsattachement[j].url), w:400,h:300});
images.push({title:item["title"],src:ImgCache.returnCachedURL(jsattachement[j].url),w:400,h:300});
}
item ["attachement"] = images;
}else
item ["attachement"] = [];
if(category=='category1')
response.category1.push(item);
else if(category=='category2')
response.category2.push(item);
//else if...
//else if...
}
}
};
checkCache function:
function checkCache (imgsrc){
ImgCache.isCached(imgsrc, function(src, success) {
if(!success){
ImgCache.cacheFile(src, function(){});
}
});
};
4th. Store to database
Here I save the parsed information to the database. On step 3 I use the returnCachedURL function for the images (which is not asynchronous) so to have the local path of the image ready even if it might not have been downloaded yet (but eventually will).
I did this:
Similar to you but, use update sql to store the image for every downloaded image. Then, I found that some of my users want to play with me, they disconnect the internet connection in the middle of image downloading! so that I have incomplete record in the sql! Jesus!
then I change to this: I create a temporary global var. e.g. tempvar = {}, then: tempvar.data1 = 'hello', tempvar.preparedatacompleted = true, tempvar.ImagesToBeDownload = 5, tempvar.ImagesDownloaded = 0, tempvar.imagearray = ......
then, everytime image downloaded, add 1 to the number, if that no. = total no., call the function that save all data and images in this tempvar to the sql.
My enemy script is linked to a prefab and being instantiated by my main script.
It kills enemies in a random order (I am jumping on them and some are not dying, not what I want).
(what I am trying to achieve is an enemy to die when I jump on its head and play a death animation.
So from this enemy script I call the other script jump <-- which is linked to my player script and get the jump Boolean value. Could the processing of jump be to slow? I need help
I tried everything)
it works but only on certain enemies any ideas why? Thanks community.
Can anyone help me find a better method?
Could someone help me maybe find if the Players y => an amount to change jump var on the enemy
Just had a perfect run, whats wrong with this its working then not then it is partly working
If I add audio, it doesn't work.
#pragma strict
var enemy : GameObject;
var speed : float = 1.0;
var enemanim : Animator;
var isdying : boolean = false;
private var other : main;
var playerhit: boolean = false;
function Start () {
other = GameObject.FindWithTag("Player").GetComponent("main");
this.transform.position.x = 8.325;
this.transform.position.y = -1.3;
enemanim = GetComponent(Animator);
enemanim.SetFloat("isdead",0);
}
function OnCollisionEnter2D(coll: Collision2D) {
if(coll.gameObject.CompareTag("distroy")){
Destroy(enemy.gameObject);
}
if(coll.gameObject.CompareTag("Player")){
playerhit=true;
}
}
function Update () {
if(other.jumped === true && playerhit==true){ *****the jumped i need
enemanim.SetFloat("isdead",1);
}
}
function FixedUpdate(){
this.transform.Translate(Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0));
this.rigidbody2D.velocity = Vector2(-5,0);
}
if(other.jumped === true && playerhit==true)
Is wrong.
It should be:
if(other.jumped == true && playerhit==true)
All 3 languages used by Unity, C#, UnityScript, and Boo, are compiled into the same IL byte code at the end. However, there are cases where UnityScript has some overhead as Unity does things in the background. One of these is that it does wrapping of access to members of built-in struct-properties like transform.position.
I prefer C#, I think it is better.
I am trying to program a very standard JS behavior for a link using an HREF
onClick handler, and I am facing a strange problem caused by what I believe to be focus/touch mode behavior on Android.
Sometimes when I click on the link, instead of executing the action, it simply becomes selected/focused, with either just a focus rectangle or even also with a filled focus rectangle (selected as opposed to just focused?).
The pseudo-code right now is
go
I have tried doing something like:
go
But I still get the same pesky problem some of the time.
Try enabling Javascript on the webview.
In the activity that holds the webview, try this...
WebView wv = (WebView) findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
I was having he same problem, but figured out it was because I did not enabled Javascript.
Try getting rid of the href attribute and see if that helps. For example, this works when viewed with the WebView component:
<p><a onClick="whereami()">Update Location</a></p>
I wonder if it's related to the onclick -- am I correct to assume that every now and then clicking any link does not follow it? To me, this seems related to the way you touch the screen (or how this is interpreted), like maybe by clicking next to the link and dragging a bit, rather than clicking on the link?
(If my assumption is correct, then this might be faulty hardware: maybe you can try on another device? Or maybe it only happens on a particular side of the link if the screen is not aligned well, and then there might be some software offset one can change?)
Try inserting this "driver" into your page code, and let us know if it works . . . It seems to be working on my site which had the same problem:
//Mouse & Touch -> Consistent Click / Mouse Commands -> Useful driver
(function() {
var isTouch = false;
var simulated_flag = 'handler_simulated';
var touch_click_array = {};
const clickMoveThreshold = 20; //Pixels
function mouseHandler(event) {
if (isTouch) {
if (!event.hasOwnProperty(simulated_flag)) {
//Unreliable mouse commands - In my opinion
var fixed = new jQuery.Event(event);
fixed.preventDefault();
fixed.stopPropagation();
}
}
else {
//Mouse commands are consistent
//TODO: generate corresponding touches
}
}
function mouseFromTouch(type, touch) {
var event = document.createEvent("MouseEvent");
event.initMouseEvent(type, true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY
, false, false, false, false, 0, null);
event[simulated_flag] = true;
touch.target.dispatchEvent(event);
};
function touchHandler(event) {
var touches = event.changedTouches
,first = touches[0]
,type = ""
;
if (!event.hasOwnProperty(simulated_flag)) {
isTouch = true;
//Simulate mouse commands
switch (event.type) {
case "touchstart":
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
touch_click_array[touch.identifier] = { x: touch.screenX, y: touch.screenY };
}
mouseFromTouch("mousedown", first);
break;
case "touchmove":
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
var id = touch.identifier;
var data = touch_click_array[id];
if (data !== undefined) {
if (Math.abs(data.x - touch.screenX) + Math.abs(data.y - touch.screenY) > clickMoveThreshold) {
delete touch_click_array[id];
}
}
}
mouseFromTouch("mousemove", first);
break;
case "touchcancel":
//Not sure what should happen here . . .
break;
case "touchend":
mouseFromTouch("mouseup", first);
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
if (touch_click_array.hasOwnProperty(touch.identifier)) {
mouseFromTouch("click", touch);
delete touch_click_array[touch.identifier];
}
}
break;
}
}
}
document.addEventListener("mousedown", mouseHandler, true);
document.addEventListener("mousemove", mouseHandler, true);
document.addEventListener("mouseup", mouseHandler, true);
document.addEventListener("click", mouseHandler, true);
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
})();
Now it isn't a 100% complete script - multi-touch would probably be a little wonky, and if you built an interface depending on touch commands, it doesn't generate those in this version. But, it fixed my link-clicking problem.
Erm - ps - it's using jQuery. If you need a non-jQuery version, you can probably just remove the new jQuery.Event from the mouseHandler() function (in other words, use the original event: var fixed = event;), and I believe most browsers would be ok. I am not exactly a js compatibility expert though.
PPS - Tested with Android 1.6
PPPS - Had to modify script to allow a threshold - actual devices were having some problems with a move event being fired during the press. Probably not ideal; if anyone wants to chime in on a better way for doing that, I'd be interested in hearing...
Recently I came across exactly the same problem. I was using the onclick on a button. Sometimes it did not execute the javascript at all. The thing that worked for me was that enable the javascript before loading a url in the webview
// Enable javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// To bind javascript code to android
mWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
mWebView.loadUrl(url);