Trying to add bulelts to javascript game ( to the spacebar) - javascript

I am almost done my game, I just need to add bullets that fire when you press space
I do have some code so far that I used from a tutorial, however it points towards the mouse. I know that I have to move it into the key-handler, but I don't know how.
I also don't know how to get rid of the wade part, I know it comes from a .json file but I want not to
Heres the code:
var nextFireTime = lastFireTime + 1 / fireRate;
var time = wade.getAppTime();
if (wade.isMouseDown() && time >= nextFireTime)
{
lastFireTime = time;
// create bullet...
}
wade.setMainLoopCallback(function()
{
// code to execute several times per second
}, 'fire');
if (wade.isMouseDown())
{
var spacemanPosition = spacemanImage.getPosition();
var spacemanSize = spacemanImage.getSize();
var sprite = new Sprite('images/alien.png');
var bullet = new SceneObject(sprite, 0, shipPosition.x, shipPosition.y - shipSize.y / 2);
wade.addSceneObject(bullet);
bullet.moveTo(shipPosition.x, -500, 600);
}
bullet.onMoveComplete = function()
{
wade.removeSceneObject(this);
};
var lastFireTime = 0;
var fireRate = 5;

To use the spacebar instead of a mousepress you have to change
wade.isMouseDown()
to
wade.isKeyDown('space')

Related

Javascript to track amount of audio listened in Qualtrics

I am currently trying to use Javascript to record how much of an audioclip someone chooses to listen to on my Qualtrics survey. However, for some reason the code that I have keeps returning all 0s (both in the console log as well as in the embedded data file). I am still very new to Javascript and would greatly appreciate another set of eyes!
Qualtrics.SurveyEngine.addOnload(function() {
/*Place your JavaScript here to run when the page loads*/
function roundNumber(number, digits) {
var multiple = Math.pow(10, digits);
var rndedNum = Math.round(number * multiple) / multiple;
return rndedNum;
};
// variables to keep track of progress
var audioListened = 0;
var audioSkipped = 0;
var lastPosition = 0;
// initialize data to 0
Qualtrics.SurveyEngine.setEmbeddedData('totalTime', 0);
var audio_element = jQuery("audio.qmedia") // HTML audio element to track
// as the audio plays, we update the data with the total amount of time listened
audio_element.ontimeupdate = function(event) {
audioListened = event.currentTime - audioSkipped;
lastPosition = event.currentTime;
Qualtrics.SurveyEngine.setEmbeddedData('totalTime', roundNumber(audioListened, 2));
};
console.log(audioListened, audioSkipped);
// when participant skips time, we keep track of this to subtract from total time
audio_element.onseeked = function(event) {
audioSkipped = (event.currentTime - lastPosition); // adds fast-forwarding, subtracts rewinding from total
};
console.log(audioListened, audioSkipped);
});
A better way to handle this is to use the played property of the media element. It gives you a TimeRanges object that you can use to figure out what parts have been watched/listened to.
for (let i=0; i<audio.played.length; i++) {
// Logs something like: 0, 5.3333
console.log(audio.played.start(i), audio.played.end(i));
}
Here's a working JSFiddle example: https://jsfiddle.net/qhryjz82/

Openlayers map jitters on dynamic centering of feature movement animation

I want to make "camera follow" effect on feature while its moves along path.
The feature is moved using requestAnimationFrame, here is the example code:
var lastFrame = +new Date;
var updateSlider = function () {
var now = +new Date, deltaTime = now - lastFrame;
trackValue += deltaTime;
self.move(trackValue);
lastFrame = now;
self.Timer = requestAnimationFrame(updateSlider);
};
updateSlider();
.move = function (timestamp) {
var point = LineString.getCoordinateAtM(timestamp);
if(point) Feature.setCoordinate(point);
this.followCamera();
};
I tried a few options of centering the view. And it works, but the problem is that the map jitters. Need help on getting rid of the jitter.
See this OL example - http://openlayers.org/en/latest/examples/geolocation-orientation.html, to see map jitters, press "Simulate"
.followCamera = function() {
var extent = Feature.getGeometry().getExtent();
A) view.set('center', ol.extent.getCenter(extent);
B) view.setCenter(ol.extent.getCenter(extent);
C) view.animate({center: ol.extent.getCenter(extent)});
D) view.fit(extent) <- Not usable in my case, because i want to zoom in/out manually
};
Also you can try this example (taken from ol examples) - https://jsfiddle.net/32z45kLo/5/ - try with and without setCenter part at moveFeature function (line 152)
Here is the video - https://youtu.be/L96HgWZi6Lo
I think the problem is that you are creating and drawing a new feature to vectorContext at each frame animation.
Instead you should create a feature and add it into a vectorLayer once, and then modify its geometry at each frame animation.
//here you define the pinpoint feature and add it to the vectorLayer
var feature = new ol.Feature();
feature.setStyle(styles.geoMarker);
vectorLayer.getSource().addFeature(feature);
var moveFeature = function(event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
if (animating) {
var elapsedTime = frameState.time - now;
// here the trick to increase speed is to jump some indexes
// on lineString coordinates
var index = Math.round(speed * elapsedTime / 1000);
if (index >= routeLength) {
stopAnimation(true);
return;
}
var currentPoint = new ol.geom.Point(routeCoords[index]);
//here you modify the feature geometry instead of creating a new feature
feature.setGeometry(currentPoint);
map.getView().setCenter(routeCoords[index]);
}
// tell OpenLayers to continue the postcompose animation
map.render();
};
working demo without jitter:
https://jsfiddle.net/32z45kLo/80/
The problem is that points on the lines are not equidistant thus the position jump from one to another but nothing inbeetween.
Look at this example to calculate points on the line: http://viglino.github.io/ol-ext/examples/animation/map.featureanimation.path.html
Using a ol.featureAnimation.Path, if you have to move the map on position change, just listen to the change event on the animated feature to get its current position:
geoMarker.on('change', function() {
map.getView().setCenter(geoMarker.getGeometry().getCoordinates());
});
You can see a working example with your code here: https://jsfiddle.net/Viglino/nhrwynzs/

Loop reload same trial instead of next one Qualtrics

I have a problem with Qualtrics Loop and Merge + Javascript. Basically, Qualtrics reload the previous trial of my loop instead of a new one.
First, here is what I try to do: I have two sets of pictures, at each loop, one picture of each set is randomly picked and displayed (randomly to the left or right side). At the end of the loop, each pictures of the set will be displayed (33 in each set, so 33 trials of the loop), without picking twice the same picture. At each trial, I also display randomly the name of the condition "in relationship" or "friends"
The problem in details:
I have coded something that seems to work quite well, except at some point: It happens that when loading the next trial of the loop, it doesn't display new pictures but instead the one that were presented in the previous trial (and also the same name of condition). This can go for a while presenting me always the same pictures, or this can just be one time.
In any case, this trial which is represented count as a trial, as my loop always ends after 33 trials, whatever if some of these are actually not new pictures presented.
This problem doesn't appear always at the same trial, and can appear several times in a loop.
It also happened that only one picture displayed is new, and the other is the one presented in the previous trial. (I really don't get how this can happen).
I coded the randomisation of picture in an empty question, just before the question where it displays the pictures. This empty question is supposed to not require to press the "next" button. When the trial are correct, this is working well, but when the next trial is going to be one "reloaded" trial, it requires to press the "next" button.
I tried the survey with Firefox and Edge, and the problem is the same.
My javascript code:
In the first question of the survey:
Qualtrics.SurveyEngine.addOnload(function () {
function shuffle(o) { //v1.0
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var FacesM_list = "IM_7U04c3TQlA7dT3D,IM_eE5iBcKfoOblbJH,IM_a3mklzA9E1OuRWl,IM_bQnoSJOGwa0vn9P,IM_5inNCVgPdHHTVSR,IM_bHlurQJWSXDRDFj,IM_3rCr2DIzW2cvqLP,IM_509x1wz7pM6PP0N,IM_3UGdsp02IcCqaSV,IM_eLrY7bwDPiT7apn,IM_3LdlHnBb6tnkBEh,IM_3pY6z6JDgaDvwq1,IM_9HtZxBS79DiOfR3,IM_03c9pDSpcwcqIyF,IM_6WGKJOzUWK4TJat,IM_2rxQPEGO7SEvsY5,IM_9YN3UCUtWEWTfGR,IM_8jZTSUAGJfuVECV,IM_9nQkFhRY2cLIVgN,IM_2abcJA7B79jt30h,IM_cD31N8XPTGliUN7,IM_0eL8iQd4PVdyuQl,IM_cuOoV9gSAe6CWd7,IM_9Nv3X7lWYEsTzsF,IM_5ccXAuuomEEyamp,IM_9mnvThFiNA5U84t,IM_e3UGNNuMdrKH8cl,IM_3aggsd5P9MMlUDr,IM_4ORY6GEMW8CmNPT,IM_50WOBkz8ADTFGHH,IM_3rqtlVBfijYCccZ,IM_3CzDsr0tYv7PH5H,IM_4SmeprjDgOeCl5b"
var FacesF_list = "IM_6fkHDs5f6ItAuk5,IM_0ri9MLjDhHxyonP,IM_bKlHtoAaxnBFlnT,IM_1WUqtBPpdhERpjf,IM_ac0yWos8tAqSMNT,IM_3xCePACn1Lq97tH,IM_6o1ZPLGUM682Au1,IM_babATdN3VtBLIsl,IM_8HSUICLvFvDXaN7,IM_0ebTztq3ML5Zh0V,IM_3lB8j5dhMs8i8ip,IM_0iC0pwDlpOkcTGt,IM_cIRojwU6sx3W7Od,IM_9ZHNbignrAfcThX,IM_8iFXvVcCqk5hemN,IM_6rrwImdl4Nss0u1,IM_6mPEaoIdazwqAWp,IM_b8lrxhsPGcc1HaR,IM_23uYWeF2gYVMsap,IM_6ycfrm5xOlewjFb,IM_7UKValFGc9Kmpp3,IM_8Bbkzsmc7CyMvqt,IM_d5S95FnSgo8j06F,IM_brXT4VUU8QJiRwN,IM_9MEkpgEmOwXhril,IM_6KG9qokOlD16GDH,IM_ellgVnYbtb8ZSbb,IM_eg6qSYMQ56z5JpX,IM_5vfbDNPdZeP1XCZ,IM_cDbOprwCUUSnUZT,IM_cumIGHXOFByV4Pz,IM_0jh2Va4JTfGsQDz,IM_0CGlFRy4dW8lDcF"
var FacesM_order = [];
for (var i = 1; i <= 33; i++) {
FacesM_order.push(i);
}
FacesM_order = shuffle(FacesM_order);
var FacesF_order = [];
for (var i = 1; i <= 33; i++) {
FacesF_order.push(i);
}
FacesF_order = shuffle(FacesF_order);
var nTrial = 0;
Qualtrics.SurveyEngine.setEmbeddedData("FacesM_order", FacesM_order.toString());
Qualtrics.SurveyEngine.setEmbeddedData("FacesF_order", FacesF_order.toString());
Qualtrics.SurveyEngine.setEmbeddedData("FacesF_list", FacesF_list.toString());
Qualtrics.SurveyEngine.setEmbeddedData("FacesM_list", FacesM_list.toString());
Qualtrics.SurveyEngine.setEmbeddedData("nTrial", nTrial.toString());
});
And in the first question of the Block with Loop and Merge:
Qualtrics.SurveyEngine.addOnload(function () {
var nTrial = Number("${e://Field/nTrial}") + 1;
var FacesF_list = "${e://Field/FacesF_list}".split(',');
var FacesM_list = "${e://Field/FacesM_list}".split(',');
var FacesF_order = "${e://Field/FacesF_order}".split(',');
var FacesM_order = "${e://Field/FacesM_order}".split(',');
var FacesF = FacesF_list[FacesF_order[nTrial]];
var FacesM = FacesM_list[FacesM_order[nTrial]];
var rand = Math.random()
if (rand < 0.5) {
var left = FacesF
var right = FacesM
} else {
var left = FacesM
var right = FacesF
}
Qualtrics.SurveyEngine.setEmbeddedData("nTrial", nTrial.toString());
Qualtrics.SurveyEngine.setEmbeddedData("left", left.toString());
Qualtrics.SurveyEngine.setEmbeddedData("right", right.toString());
this.clickNextButton.delay(.00000000000001);
});
Thanks a lot for your help!

a strange behavior in Phaser with javascript

firstly
I am not beginner at game development at all - but beginner in web game development specially
I started with Phaser as it looks good and optimized for mobile games
anyway ..
I have a strange behavior with my game - I put a rectangle and trying to move it (when I debugged the X axis already changes correctly , but I can't see the rectangle move!!)
my codes
var game = new Phaser.Game(window.innerWidth,window.innerHeight,Phaser.AUTO);
var colors = ["#FF0000" , "#00FF00" , "#0000FF" , "#FFFF00" , "#00FFFF" , "#FFFF00"];
var lst;
var hlprs = [];
var gameState = {
preload: function () {
this.game.stage.backgroundColor = "#FFFFFF";
},
create: function () {
for (var i = 0 ; i < 8 ; i++)
{
hlprs[i] = new Phaser.Rectangle((i*200),0,100,20);
hlprs[2*i + 1] = new Phaser.Rectangle((i*200),window.innerHeight - 20,100,20);
game.debug.geom(hlprs[i] , colors[Math.floor((Math.random() * 6))]);
game.debug.geom(hlprs[2*i + 1] , colors[Math.floor((Math.random() * 6))]);
}
},
update: function ()
{
moving();// it calls moving function and X axis is changes but (the rectangle does not move !!!)
}
};
function moving()
{
for (var i = 0 ; i < 8 ; i++)
{
hlprs[i].offset(-1,0);
hlprs[2*i + 1].offset(-1,0);
}
}
game.state.add('GameState' , gameState);
game.state.start('GameState');
Without testing it, I'd guess that what happens is the following: you create a bunch of shapes and do a single call to game.debug.geom() for each of the shapes. In the meantime the shapes do start moving, but since you never call game.debug.geom() again, you never see anything moving.
If you intend to use methods from game.debug, they should usually go inside the render() method of your state (which will be called once for every frame).
Note that the debug methods are to be used, well, for debugging. The proper way of displaying a shape is by making a sprite or an image (in which case you won't have to update anything manually since Phaser will handle it).
Since the update() function calls moving() you might want to have your game.debug commands within moving
function moving()
{
for (var i = 0 ; i < 8 ; i++)
{
hlprs[i].offset(-1,0);
hlprs[2*i + 1].offset(-1,0);
// update here
game.debug.geom(hlprs[i] , colors[Math.floor((Math.random() * 6))]);
game.debug.geom(hlprs[2*i + 1] , colors[Math.floor((Math.random() * 6))]);
}
}
Here's a demo: https://jsfiddle.net/user2314737/J5fUE/253/

jQuery 2.1.0 | Display elements incrementally

I need to display rows of buttons incrementally from top to bottom in a scrollable parent div. These rows of buttons are created using a replace method applied onto a text string converted to html. Since I can have 500+ more rows of buttons to create and display, the text-to-html conversion can take a few seconds or longer, which freezes the UI during conversion. The code below uses a setInterval which unlocks the UI and provides a cool way of "animating" the gradual display of button rows. Problem is, currently, the whole set of rows is repeated at each setInterval, that's not what I want, I can't figure out what to do next. I need each individual row to be displayed incrementally without repeating, from top to bottom, in the order provided by the string, until the length of array is met. The scrolable parent div is a fixed height of 300px. Maybe a Lazy loading method would be better? Any help solving this issue is appreciated.
DEMO fiddle
var placeholder = $('#placeholder');
placeholder.html(placeholdertohtml(placeholder));
function placeholdertohtml(placeholder){
placeholder.html(placeholder.text().replace(/((\d{2},\d{2}))/g, function(match, number){
var blocks = placeholder.text().split(',').length;
console.log(blocks);
var el = number.substr(0,5).split(',');
var prefix = el[0];
var suffix = el[1];
var t = setInterval(function(){
if (blocks) {
var content = '<p><button>'+prefix+'</button><button>'+suffix+'</button></p>';
$('#placeholder').append(content);
blocks--;
} else {
clearInterval(t);
}
}, 100);
}));
}
So, I reworked your code using for loops instead of the replace function to fix the problem.
Here is a working codepen
I basically made a loop that built up an array of html to add:
var numberOfPairs = placeholder.text().match(/((\d{2},\d{2}))/g).length;
var countdown = numberOfPairs;
var string = placeholder.text();
var elements = [];
for(var i = 0; i < numberOfPairs; i++) {
var pair = string.substring(5 * i + 1, (5 * i) + 6).split(',');
var prefix = pair[0];
var suffix = pair[1];
elements.push('<p><button>'+prefix+'</button><button>'+suffix+'</button></p>');
}
And then looped over the elements with your interval function to get the same "loading" effect:
var elementIndex = countdown;
var t = setInterval(function(){
if (countdown >= 0) {
$('#placeholder').append(elements[(countdown - elementIndex) * -1]);
countdown--;
} else {
clearInterval(t);
}
}, 100);

Categories