I'm writing a little javascript game and trying to make it work with a gamepad. The gamepad works (on linux at least). I wrote this code:
var gamePad;
var checkForGamepad;
function startPolling() {
checkForGamepad= setInterval(function () {
gamePad= navigator.webkitGetGamepads && navigator.webkitGetGamepads()[0]
},20)}
function stopPolling(){
clearInterval(checkForGamepad);
checkForGamepad=null;
}
This is for starting to check if there is a gamecontroller connected and I can also stop it (for when I'm in the menu for example). But now I want to write an event recorder. I wrote already one for the keyboard, but that's easy because you have a 'keyup' event. Does anybody have an idea, how to write an event recorder for a gamepad?
My event recorder for my keyboard looks like this:
function gameNavigationKey(evt){
switch (evt.keyCode){
case 32: // spacebar was pressed
//change the gravity
// do some other stuff
break;
.
.
.
}
And in the code when I start my gameloop(), I also call window.addEventListener('keyup',gameNavigationKey,true)
So I want basically the same style for my event recorder with my gamepad.
I know I can read values of keys being pressed on the gamepad using gamePad.buttons[0] returns 0 when not pressed 1 while being pressed. So I think I need to remember the previous state of my key, but still, don't have an idea how to start.
Can somebody please help me creating this event recorder?
Thanks in advance
In the current implementation of the Gamepads with Chrome, at every update you have to call:
navigator.webkitGetGamepads();
It will give you the latest status of the pads. If you want to implement something out of it you will need to compare with the previous status and make your own events.
Firefox doesn't require to call getGamepads at every frame, but updates the object automatically after you implement the events gamepadconnected and gamepaddisconnected.
You can find extra information here:
http://www.html5rocks.com/en/tutorials/doodles/gamepad/
https://developer.mozilla.org/en-US/docs/Web/Guide/API/Gamepad
Related
Hi I know the title of my post is quite tricky, so let me talk about it in detail here. I'm working on html+js page that gets the orientation value from my smartphone. The two devices are connected through google firebase, and it gets the realtime orientation value when my smartphone is on that page. I'm having trouble with connecting this value with the function of triggering the arrow keys.
For example, if the beta value is more than 0, up-key is triggered, etc.
I'm trying to use this orientation value to trigger up, down, left, right keys to be pressed accordingly, but I couldn't find any clue for it. What I get from google or stackflow was usually about connecting functions with the keyboard-events, but what I'm trying to do is the opposite; triggering keyboard-events based on conditions of the orientation values.
I'd appreciate if anyone can give me some clues or quick examples, so that I can twick. Sorry that I couldn't link any jsfiddles or part of the code since it's already connected with my firebase!
p.s. the code part I'm showing below is the part I checked it's working! I checked the orientations values are valid.
const controlAlpha = document.querySelector("#alpha").innerText;
const controlBeta = document.querySelector("#beta").innerText;
const controlGamma = document.querySelector("#gamma").innerText;
betaControl = function(){
if (textBeta<0){
console.log("beta under 0");
}
else{
console.log("beta over 0");
}
}
betaControl();
Fiddle here: https://jsfiddle.net/chpaeeL9/1/
Microsoft Bot Framework has a webchat module that allows you to talk to your bot.
When the user clicks the Say Hi button, I want to place some text into the webchat's textbox, and click the Send button inside the webchat using JavaScript.
Sounds like something too easy, but it wasn't. Here's the code that I currently have, and it doesn't work: the click event somehow is not triggered.
$('#sayhibutton').click(function() {
$('.wc-console').addClass('has-text'); // works
$('.wc-shellinput').val("Hi bot!").change(); // works
$('.wc-send').click(); // doesn't work!
$('.wc-send svg').click(); // doesn't work either
});
Update: if that helps, it seems the interface is written using React.
Update: my question is different from my previous question about how to avoid iframes in webchat.
OK, for the lack of a better option my solution was a pretty dirty and ugly one.
Save the code in botchat.js into a file and reference that saved file from the HTML, rather than the CDN version.
Pretty-print the file in Chrome and find the line that says:
e.prototype.sendMessage = function() {
this.props.inputText.trim().length > 0 && this.props.sendMessage(this.props.inputText)
}
Replace the middle line with this:
this.textInput.value.trim().length > 0 && this.props.sendMessage(this.textInput.value)
This basically means to take the message text from this.textInput.value rather than from this.props.inputText, or in other words, take it directly from the textinput's DOM node.
Somehow triggering the change event on a textbox doesn't cause an actual change event on the textbox, which is why we need to do this.
this is an issue with react try this,
var input = document.getElementsByClassName("wc-shellinput")[0];
var lastValue = input.value;
input.value = 'YOUR MESSAGE';
var event = new CustomEvent('input', { bubbles: true });
// hack React15
event.simulated = true;
// hack React16
var tracker = input._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
input.dispatchEvent(event);
//send the message
$(".wc-send:first").click();
to read more see this post: https://github.com/Microsoft/BotFramework-WebChat/issues/680
I'm using MediaCapture in javascript to capture my camera.
I have a Camera class with an initCamera function. The problem is, if I try to re-init my camera in a short time period I will get this error: Hardware MFT failed to start streaming due to lack of hardware resources.
Now I get that this means my camera is still in use. The thing I want to know is:
How do I properly close my camera
How do I check if my camera is in use or unavailable
Here is a piece of code:
function Camera() {
var that = this;
this.mediaCaptureElement = null;
this.initCamera = function() {
if (!that.mediaCaptureElement) {
that.mediaCaptureElement = new Windows.Media.Capture.MediaCapture();
that.mediaCaptureElement.addEventListener("failed", function (e) {
console.warn("The camera has stopped working");
}
that.mediaCaptureElement.initializeAsync().then(function() {
that.mediaCaptureElement.videoDeviceController.primaryUse = Windows.Media.Devices.CaptureUse.photo;
that.getCameraResolution();
that.orientationChanged();
that.startCamera();
});
}
};
The way I re-open my camera currently is by overwriting the camera instance with a new instance of the Camera class.
Thanks in advance.
I had the same problem using MediaCapture in C#.
I had to call Dispose() after StopPreviewAsync in order to correct it :
await cameraControler.MediaCaptureInstance.StopPreviewAsync(); cameraControler.MediaCaptureInstance.Dispose();
Have you seen the Camera Starter Kit UWP sample? It comes in a JS flavor too!
If you want to be able to reliably access the camera shortly after being done using it, you need to make sure you're cleaning up all resources properly. From the code that you've shared, it seems like you're letting the system take care of this, which means your app might be coming back before the system is done closing out all resources.
You should take care of:
Stop any recordings that may be in progress
Stop the preview
Close the MediaCapture
Have a look at the cleanupCameraAsync() method from the sample I linked above for an example on how to implement this.
According to this question, when we set the window.location, javascript will "stop" executing or turn into a race condition.
Sometimes we need to fire window.location = SOMESCH://xxx multiple times inside a WebView to send "Notifications" back to our app. For example setting window.location = myapp://loginButtonEnabled?e=1 to tell the app that the user had filled in some nessasary info and can start login. It seems to be impossible to do something like this:
function(){
window.location = myapp://loginButtonEnable?e=1;
window.location = myapp://hideHintView;
.....
window.location = myapp://theLastThing;
}
Only the last window.location = myapp://theLastThing will be fired and then the execution of Javascript will stop(though we stopped the redirecting in our app by returning NO in webView:shouldStartLoadWithRequest:navigationType:).
I found it interesting that PhoneGap made this possible by using a dispatching queue, but I still haven't figure out why it works, anybody knows the trick??
BTW, is there a simple way to "resume" the execution after setting location? It will be much better than using an operation queue.
You need to give the event loop a chance to respond to the location change each time. The typical way of doing this is using a setTimeout with a small/zero delay, which has the effect of moving execution to the next event loop tick. Try something like this:
var q=[];
function dequeue() {
window.location='myapp://'+q.shift();
if (q.length>0) setTimeout(dequeue,0);
}
function notifyApp(cmd) {
q.push(cmd);
if (q.length==1) setTimeout(dequeue,0);
}
notifyApp('loginButtonEnable?e=1');
notifyApp('hideHintView');
notifyApp('theLastThing');
As for javascript execution stopping, setting window.location shouldn't have this effect unless it actually results in a page change - perhaps try using the technique above and see if your javascript continues after the last notifyApp() call.
EDIT: Another approach to this issue is to create temporary iframes instead of changing the location of the current page - see for example
Triggering shouldStartLoadWithRequest with multiple window.location.href calls
I am trying to mimic key press events, for instance Ctrl+D on a button click.
It would be great if someone can point me in the right direction on how to achieve the same.
You're not allowed to do that. Imagine all the havoc I could wreak if I could send CTRL-ALT-DEL at will.
The code for triggering a custom event (in this instance, Ctrl+d) is as follows:
var evt = jQuery.Event("keypress");
evt.keyCode = 100; // d
evt.ctrlKey = true;
$(document).trigger(evt);
NB that, as the other answers have said, this will be limited in its impact. You won't be able to affect normal browser functions in this way.
That would be "firing events", though I'm leaving the exercise to you to find the right code.
As the other guy said, you cannot do any kind of thing with it. It is purposefully limited.
However, let's say I have a wysiwyg editor in javascript, which supports receiving ctrl+s and saving, you should be able to fire that yourself and make it save anyway.
At the end, it's a matter of context (focus), and which sometimes fails (again, purposefully).
This will trigger ctrl+d
function btnClick(){
document.dispatchEvent(new KeyboardEvent('keydown', {'key': 'd', 'ctrlKey': true}));
}