I simply insert following codes in a clean base(at the final of HelloWorld::init()) produced by cocos new:
auto kl = EventListenerKeyboard::create();
kl->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event) {
CCLOG("%s> keyCode=%d",__FUNCTION__,keyCode);
};
auto ed = Director::getInstance()->getEventDispatcher();
ed->addEventListenerWithSceneGraphPriority(kl,this);
On windows, it worked well. But nothing happened on android.
Log with value of keyCode should be left in logcat, I think.
Do I miss anything?
Approach One:
If you just need to handle keyboard as key-event, It's as easy as these below lines of code:
HelloWorld::init()
{
...
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_UP_ARROW: /*Jump maybe*/ break;
case EventKeyboard::KeyCode::KEY_DOWN_ARROW: /*Crouch maybe*/ break;
case EventKeyboard::KeyCode::KEY_RIGHT_ARROW: /*Move Right maybe*/ break;
case EventKeyboard::KeyCode::KEY_LEFT_ARROW: /*Move Left maybe*/ break;
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
...
return true;
}
I think it's clear enough not to need any extra description.
Approach Two: if you need an input box that user/player can enter string with keyboard and you get what is entered, I recommend to use TextField which is available in cocos2d v3 ( and with some difficulty in v2) and has a full functionality. You can create and initial one of them as:
auto textField = cocos2d::ui::TextField::create("hint: enter here","Arial" , 30);
textField->setTextHorizontalAlignment(cocos2d::TextHAlignment::CENTER);
textField->setTextVerticalAlignment(cocos2d::TextVAlignment::CENTER);
textField->setColor(Color3B(100,100,100));
textField->setMaxLength(10);
textField->setMaxLengthEnabled(true);
textField->setTouchAreaEnabled(true);
textField->setTouchSize(Size(200,400));
textField->setPosition(...);
textField->addEventListener(CC_CALLBACK_2(HelloWorld::textFieldEvent, this));
this->addChild(textField, 10);
You can get entered data any time with std::string enteredData= textField->getString();
You can also do something when user entering text with two event as :
void HelloWorld::textFieldEvent(Ref *pSender, cocos2d::ui::TextField::EventType type)
{
switch (type)
{
case cocos2d::ui::TextField::EventType::ATTACH_WITH_IME:
{
textField->setColor(Color3B::BLACK);
// or whatever elese
break;
}
case cocos2d::ui::TextField::EventType::DETACH_WITH_IME:
{
textField->setColor(Color3B(100,100,100));
// or whatever elese
break;
}
}
}
Enjoy !
Related
Is it valid to put expressions in a case statement? I have this switch case statement.
var switchValue:String = StatusUpdateErrorEvent.UPDATE_ERROR;
switch (switchValue) {
case caseValue: { // it's implied here that (switchValue==caseValue)
}
case StatusUpdateErrorEvent.UPDATE_ERROR: {
}
case event is StatusUpdateErrorEvent && StatusUpdateErrorEvent.UPDATE_ERROR: {
}
// is this what I should do if I add my own expression?
case event is StatusUpdateErrorEvent && StatusUpdateErrorEvent.UPDATE_ERROR==type: {
}
}
It doesn't throw any errors when I add an expression is the switchValue==caseValue expression thrown out?
switch (switchValue) {
case caseValue:
//1
break;
case StatusUpdateErrorEvent.UPDATE_ERROR:
//2
break;
case event is StatusUpdateErrorEvent && StatusUpdateErrorEvent.UPDATE_ERROR:
//3
break;
case event is StatusUpdateErrorEvent && StatusUpdateErrorEvent.UPDATE_ERROR == type:
//4
break;
}
You need to use "break;" after every case. If not, all other breaks after will be executed. It can e also "return;" if you just want to exit function after break.
Other thing is that you use "case" in a very weird way, just like they are if's. Don't put boolean comparison there like that. It's place for values.
I'm using background file transfer and background audio player.
in the TransferStatusChanged event i save the file to the isolated storage then play it with the audio player,
It works fine if the application is active and i want to do the same if the application is not active.
In WP8.0 it isn't possible as your TransferStatusChanged is in your App process which is stopped when you navigate away from it:
When the user navigates forward, away from an app, after the Deactivated event is raised, the operating system will attempt to put the app into a dormant state. In this state, all of the application’s threads are stopped and no processing takes place, but the application remains intact in memory.
You can make it work under LockScreen by disabling IdleDetection but it won't work when your App is put into dormant/tombstoned state.
You may consider to start playing when you activate the App or put some logic in BAP where you can check for example upon TrackChange if the file was downloaded and then play it.
edit
thanks to #Romasz suggestion of use empty track to play while the file complete downloading
then in TrackChange i check if the file downloaded and remove it from the download queue -this can be done in the audio background- things work fine now. here is some code
private AudioTrack GetNextTrack(bool isStart = false)
{
AudioTrack track = null;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isStart)
{
currentSongIndex = -1;
}
currentSongIndex++;
if (currentSongIndex == _ProgressList.Count())
{
//currentSongIndex = 0;
return track;
}
if (ISF.FileExists("shared/transfers/" + _ProgressList[currentSongIndex].FileName))
{
var request = requests.Where(it => it.Key == _ProgressList[currentSongIndex].FileName).FirstOrDefault().Value;
if (request != null)
{
bool isDone = ProcessTransfer(request, _ProgressList[currentSongIndex].Directory);
if(!isDone )
{
if(request.BytesReceived > LastDownloadedSize)
{
NumberOfTrialsToLoadNextTrack = 0;
LastDownloadedSize = request.BytesReceived;
}
else
{
++NumberOfTrialsToLoadNextTrack;
}
}
}
}
else
{
++NumberOfTrialsToLoadNextTrack;
}
if (ISF.FileExists(_ProgressList[currentSongIndex].Directory+_ProgressList[currentSongIndex].FileName))
{
track = playList[currentSongIndex];
NumberOfTrialsToLoadNextTrack = 0;
LastDownloadedSize = 0;
}
else
{
currentSongIndex--;
if (NumberOfTrialsToLoadNextTrack < 10)
{
track = new AudioTrack(new Uri("halfsec.mp3", UriKind.Relative),
"empty",
"empty",
"empty",
null);
}
}
}
return track;
}
private bool ProcessTransfer(BackgroundTransferRequest transfer, string directory = "")
{
bool isDone = false;
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
RemoveTransferRequest(transfer.RequestId);
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
string filename = transfer.Tag;
System.Diagnostics.Debug.WriteLine(directory + filename);
if (isoStore.FileExists(directory + filename))
{
isoStore.DeleteFile(directory + filename);
}
if (isoStore.FileExists(transfer.DownloadLocation.OriginalString))
{
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, directory + filename);
}
}
isDone = true;
}
else
{
RemoveTransferRequest(transfer.RequestId);
if (transfer.TransferError != null)
{
}
}
break;
}
return isDone;
// NotifyComplete();
}
private void RemoveTransferRequest(string transferID)
{
// Use Find to retrieve the transfer request with the specified ID.
BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);
// try to remove the transfer from the background transfer service.
try
{
BackgroundTransferService.Remove(transferToRemove);
}
catch (Exception)
{
}
}
protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
{
switch (playState)
{
case PlayState.TrackEnded:
player.Track = GetNextTrack();
break;
case PlayState.TrackReady:
player.Play();
break;
case PlayState.Shutdown:
// TODO: Handle the shutdown state here (e.g. save state)
break;
case PlayState.Unknown:
break;
case PlayState.Stopped:
break;
case PlayState.Paused:
break;
case PlayState.Playing:
break;
case PlayState.BufferingStarted:
break;
case PlayState.BufferingStopped:
break;
case PlayState.Rewinding:
break;
case PlayState.FastForwarding:
break;
}
NotifyComplete();
}
this code in the AudioPlayer class, the files added to the download queue in the xaml.cs normally
I got this function (in the document class)
public function kyz(event:KeyboardEvent):void{
trace(event.keyCode);
switch (event.keyCode){
case 65:{
if (ppm.currentFrame<200 || ppm.currentFrame>300) {
ppm.gotoAndStop(301);
ssm.gotoAndStop(302);
llm.gotoAndStop(302);
mmm.gotoAndStop(302);
myTimer.stop();
pd.play();
}else {
pd.play();
ppm.gotoAndPlay(10);
tlrnc-=10;
}
break;
}
case 68:{
if (ssm.currentFrame<200 || ssm.currentFrame>300) {
ssm.gotoAndStop(301);
ppm.gotoAndStop(302);
llm.gotoAndStop(302);
mmm.gotoAndStop(302);
myTimer.stop();
mTimer.stop();
sd.play();
}else {
sd.play();
ssm.gotoAndPlay(10);
tlrnc-=10;
}
break;
}
case 74:{
if (llm.currentFrame<200 || llm.currentFrame>300) {
llm.gotoAndStop(301);
ppm.gotoAndStop(302);
ssm.gotoAndStop(302);
mmm.gotoAndStop(302);
myTimer.stop();
mTimer.stop();
ld.play();
}else {
ld.play();
llm.gotoAndPlay(10);
tlrnc-=10;
}
break;
}
case 76:{
if (mmm.currentFrame<200 || mmm.currentFrame>300) {
mmm.gotoAndStop(301);
ppm.gotoAndStop(302);
ssm.gotoAndStop(302);
llm.gotoAndStop(302);
myTimer.stop();
mTimer.stop();
md.play();
}else {
md.play();
mmm.gotoAndPlay(10);
tlrnc-=10;
}
break;
}
}
}
that receives key event's and do stuff. now I'm trying to pass they keyCode from another function (to avoid changing the whole code for adding click functionality) got any suggestions?
you could dispatch a KeyboardEvent
stage.dispatchEvent(
new KeyboardEvent(KeyboardEvent.KEY_DOWN, true, false, myCharCode, myKeyCode));
just add the needed keyCode as a parameter
You cannot send any Keyboard or Mouse event without interactivity with user. You can handle this in another private function:
private function keyDownHandler(event : KeyboardEvent) : void {
this.handleEvent(event.keyCode);
}
private function handleEvent(keyCode : uint) : void {
//some actions
}
And when you need to make specific actions, you can just call handleEvent function without user side interactivity.
I am new to ActionScripting but I have done some Java. I was told they are kinda similar. I am coding my swf file with some AS3 integrated.
function init():void{
// do something
}
function init(var string:String):String{
// do something else
}
is this not allowed in AS? If not, is there another way of handling it besides?
Thanks in advance.
Yes, you can override functions. But the example you gave is not overriding - it's overloading. For overriding a function, you basically just create a function with the same signature and everything in a subclass and add the word "override" right before it.
You can't directly overload a function though. If you want a variable number of parameters, you have to use optional parameters instead. Like this:
function init(str:String = null):String
{
if (str == null)
{
// do one thing
return null;
}
else
{
// do another thing
return "someString";
}
}
And that's about the best you're going to be able to do in AS3. The inability to overload functions, at least strictly speaking, is a fairly common complaint and obvious shortcoming of the language.
Do you mean method overloading? Actionscript, sadly, does not support this.
To get around it, you can use default parameters, or just make your parameters a bit less constraining. This answer has some details on that.
You could try this:
function init(var string:String = "Default value"):String{
// do something
}
Actionscript does not support method overloading. However, based on the answer to this question you have other options.
If you just want to be able to accept any type, you can use * to
allow any type:
function someFunction( xx:*, yy:*, flag:Boolean = true )
{
if (xx is Number) {
...do stuff...
} else if (xx is String) {
...do stuff...
} else {
...do stuff...
}
}
If you have a large number of various parameters where order is
unimportant, use an options object:
function someFunction( options:Object )
{
if (options.foo) doFoo();
if (options.bar) doBar();
baz = options.baz || 15;
...etc...
}
If you have a variable number of parameters, you can use the ...
(rest) parameter:
function someFunction( ... args)
{
switch (args.length)
{
case 2:
arr = args[0];
someBool = args[1];
xx = arr[0];
yy = arr[1];
break;
case 3:
xx = args[0];
yy = args[1];
someBool = args[2];
break;
default:
throw ...whatever...
}
...do more stuff...
}
For cases where you need to call a common function to a number of
classes, you should specify the interface common to each class:
function foo( bar:IBazable, flag:Boolean )
{
...do stuff...
baz = bar.baz()
...do more stuff...
}
This AS3 function works for normal methods and getter methods:
public function MyClassTestAPI(functionName:String, ...rest):* {
var value:*;
try {
switch(rest.length) {
case 0:
value = myObj[functionName];
break;
case 1:
value = myObj[functionName].call(functionName, rest[0]);
break;
case 2:
value = myObj[functionName].call(functionName, rest[0],rest[1]);
break;
default:
throw("Cannot pass more than 2 parameters (passed " + rest.length + ")");
}
}
return value;
}
Sample usage:
this.MyClassTestAPI("Foo", "arg1"); // tests function Foo(arg1:String):String
this.MyClassTestAPI("MyProperty"); // tests function get MyProperty():String
this.MyClassTestAPI("MyProperty", "new value");// tests function set MyProperty(val:String):void
The third call does not work (throws exception).
How can I make it work for setter methods as well?
Thanks!
edit:
This is a version that works, except with getter and setter that have additional parameters.
It is ok for my needs:
public function MyClassTestAPI(functionName:String, ...rest):* {
var value:*;
try {
if (typeof(this.mediaPlayer[functionName]) == 'function') {
switch(rest.length) {
case 0:
value = myObj[functionName].call(functionName);
break;
case 1:
value = myObj[functionName].call(functionName, rest[0]);
break;
case 2:
value = myObj[functionName].call(functionName, rest[0],rest[1]);
break;
default:
throw("Cannot pass more than 2 parameters (passed " + rest.length + ")");
}
} else {
switch(rest.length) {
case 0:
value = myObj[functionName];
break;
case 1:
myObj[functionName] = rest[0];
break;
default:
throw("Cannot pass parameter to getter or more than one parameter to setter (passed " + rest.length + ")");
}
}
}
return value;
}
Setter functions works as variables, so you can't use it in this way:
myProperty.call( "new value" );
Your function for variables is pointless, because you just have to do a value assignment:
myProperty = "new value";
By the way you can include it in your function in two ways:
create a third parameter what tells your function it is a function or variable
create the value assignment in the catch section
You are currently passing only one string with value "new value"
This should do the trick:
this.MyClassTestAPI("MyProperty", "new","value");
For more information on this matter check the Adobe LiveDocs at:
http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_19.html
Cheers