Here is my code regarding tilesprite & a player, player should not pass through tilesprite but unfortunately my code is not working, i tried all ways but couldn't achieve the desired result, i don't know why tile2.body.immovable=true; flag not working.
var main = {
preload: function () {
this.game.load.image('ground', 'images/ground.jpg');
this.game.load.image('bg', 'images/gabg.jpg');
this.game.load.atlasJSONHash('mover', 'images/sheet.png', 'images/sprites.json');
},
create: function () {
this.game.physics.startSystem(Phaser.Physics.ARCADE);
cursor = this.game.input.keyboard.createCursorKeys();
tile1 = game.add.tileSprite(0, 10, 1365, 582, 'bg');
tile2 = game.add.tileSprite(0, 590, 1366, 91, 'ground');
player = this.game.add.sprite(50, 550, 'mover');
player.frame = 0;
player.anchor.setTo(0.5, 0.5);
while (i < 11) {
anim.push(i)
i++;
}
player.animations.add('move', anim, 20, true);
this.game.physics.arcade.enable(player);
this.game.physics.arcade.enable(tile2);
tile2.body.immovable = true;
tile2.body.allowGravity = false;
player.body.gravity.y = 800;
},
update: function () {
this.game.physics.arcade.collide(tile2, player);
tile1.tilePosition.x += -1;
tile2.tilePosition.x += -4;
this.move();
},
move: function () {
if (cursor.up.isDown) {
player.body.velocity.y = -200;
player.animations.stop('move');
}
else {
player.animations.play('move');
}
},
};
var game = new Phaser.Game(1366, 768, Phaser.CANVAS, 'gamediv');
this.game.state.add('main', main);
this.game.state.start('main');
var anim = [];
var cursor, i=0;
var tile1;
var tile2;
var player;
Which version of Phaser are you using? Could it be related to this bug in 2.3.0?
http://www.html5gamedevs.com/topic/13856-problem-with-collide-method-from-physics-arcade-in-different-versions-of-phaser/?p=79032
Related
I have JSON file contain games objects, I want to get top 5 games that have the highest total playtime between users.
I tried to get all objects by reading the file using file system in nodejs :
const queryGames = async () => {
let data = fs.readFileSync(path.resolve(__dirname, '../../games.json'))
let games = JSON.parse(data)
return games
}
/**
* Query for top games by play time
* #returns {Promise<QueryResult>}
*/
const selectTopByPlaytime = async () => {
}
this is the json file : https://jsoneditoronline.org/#left=cloud.3b82169327044c04b7207fa186aee85b&right=local.tiniqu
something like this should work.
const gamePlayData = require('./gamePlay.json').data
/**
* Query for games and time
* #returns {
'League of legends': 1650,
'World of warcraft': 2300,
'Dark Souls': 218,
'The Witcher 3: Wild Hunt': 987,
etc....
}
*/
const getGamePlayTimes = () => {
gamePlayTimes = {}
gamePlayData.forEach( (playData) => {
const gameName = playData.game
if(gamePlayTimes[gameName]) {
gamePlayTimes[gameName] += playData.playTime
}
else {
gamePlayTimes[gameName] = playData.playTime
}
})
return gamePlayTimes;
}
const getGamesAndTimesAsList = (playTimes) => {
let gamesWithTimeArr = [];
let i = 0;
for(let game in playTimes) {
let gameAndPlayTime = {game: "", playTime: 0};
gameAndPlayTime.game = game;
gameAndPlayTime.playTime = playTimes[game];
gamesWithTimeArr[i++] = gameAndPlayTime
}
return gamesWithTimeArr;
}
const reverseBubbleSort = (a, par) => {
let swapped;
do {
swapped = false;
for (var i = 0; i < a.length - 1; i++) {
if (a[i][par] < a[i + 1][par]) {
var temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return a;
}
sortedArr = reverseBubbleSort(getGamesAndTimesAsList( getGameAndPlayTimes() ) , 'playTime')
const top5 = sortedArr.slice(0, 5);
console.log(top5);
==== SOLVED ====
To be 100% honest I'm not sure what I did, but I have a fully working audio bar visualizer based on desktop audio. I went back to the original codepen (link below) I started working off of and edited everything as needed to accept a media stream, and it works.
Full Code
const {desktopCapturer} = require('electron')
desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
if (error) throw error
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name === 'Entire screen') {
navigator.mediaDevices.getUserMedia({
audio: { mandatory : { chromeMediaSource: 'desktop' }},
video: { mandatory : { chromeMediaSource: 'desktop' }}
})
.then((stream) => handleStream(stream))
return
}
}
})
function handleStream (stream)
{
const context = new AudioContext()
let src = context.createMediaStreamSource(stream)
let analyser = context.createAnalyser()
let canvas = document.getElementById("canvas")
canvas.width = window.innerWidth
canvas.height = window.innerHeight
let ctx = canvas.getContext("2d")
src.connect(analyser)
analyser.fftSize = 256
let bufferLength = analyser.frequencyBinCount
let dataArray = new Uint8Array(bufferLength)
let WIDTH = canvas.width
let HEIGHT = canvas.height
let barWidth = (WIDTH / bufferLength) * 2.5
let barHeight
let x = 0
function renderFrame()
{
requestAnimationFrame(renderFrame)
x = 0
analyser.getByteFrequencyData(dataArray)
ctx.fillStyle = "#000"
ctx.fillRect(0, 0, WIDTH, HEIGHT)
for (let i = 0; i < bufferLength; i++)
{
barHeight = dataArray[i]
let r = barHeight + (25 * (i / bufferLength))
var g = 250 * (i/bufferLength)
var b = 50
ctx.fillStyle = `rgb(${r}, ${g}, ${b})`
ctx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight)
x += barWidth + 1
}
}
renderFrame()
}
Codepen I used as a starting point
https://codepen.io/nfj525/pen/rVBaab
Original Post
I'm working on setting up a desktop visualizer that will graph the users desktop audio.
desktopCapture appears to be grabbing the media as sending it to a video tag displays the stream, along with an echo of the media. Since I only need the audio, I'm setting the mediaStraem to an AudioContext MediaStreamSource, which also appears to be working as I get an audio echo if I connect the analyser to the ctx destination. The issue I'm running into is when I try to get the frequency data its returning an array of only 0s. Below is my current code
const {desktopCapturer} = require('electron')
desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
if (error) throw error
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name === 'Entire screen') {
navigator.mediaDevices.getUserMedia({
audio: {
mandatory : {
chromeMediaSource: 'desktop'
}
},
video: {
mandatory: {
chromeMediaSource: 'desktop',
}
}
})
.then((stream) => handleStream(stream))
return
}
}
})
function handleStream (stream) {
let audioCtx = new AudioContext();
let source = audioCtx.createMediaStreamSource(stream);
let analyser = audioCtx.createAnalyser()
//uncommenting results in echo, but still all 0s
//analyser.connect(audioCtx.destination)
analyser.fftSize = 256
let bufferLength = analyser.frequencyBinCount
let dataArray = new Uint8Array(bufferLength)
console.log(dataArray)
}
===== EDIT =====
I've been able to get this working; kind of but am still running into a slight issue.
1) I had connect the source and the analyzer with
source.connect(analyser)
2) Had to fill the dataArray with time domain with
getByteTimeDomainData
3) Outstanding issue is when there is no media playing the dataArray is filled with values of 126, 127, & 128 making the bars "dance" at almost full height.
4) The FPS also seems extremely fast, but have some plans to fix that
Current somewhat working code :
const {desktopCapturer} = require('electron')
desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
if (error) throw error
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name === 'Entire screen') {
navigator.mediaDevices.getUserMedia({
audio: {
mandatory : {
chromeMediaSource: 'desktop'
}
},
video: {
mandatory: {
chromeMediaSource: 'desktop',
}
}
})
.then((stream) => handleStream(stream))
return
}
}
})
function handleStream (stream) {
const audioCtx = new AudioContext()
let source = audioCtx.createMediaStreamSource(stream)
let analyser = audioCtx.createAnalyser()
source.connect(analyser) //Had To Connect Source To Analyser
analyser.fftSize = 128
let bufferLength = analyser.frequencyBinCount
let dataArray = new Uint8Array(bufferLength)
let canvas = document.getElementById("canvas")
canvas.width = window.innerWidth
canvas.height = window.innerHeight
let canvasCtx = canvas.getContext("2d")
let WIDTH = canvas.width;
let HEIGHT = canvas.height;
let barWidth = (WIDTH / bufferLength);
let barHeight;
let x = 0;
function draw() {
var drawVisual = requestAnimationFrame(draw)
analyser.getByteTimeDomainData(dataArray) //added to the draw to fill the dataArray
canvasCtx.fillStyle = "#000";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
var x = 0;
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
let r = 50
let g = 250
let b = 50
canvasCtx.fillStyle = `rgb(${r}, ${g}, ${b})`
canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
}
draw()
}
The terminal out is:
but actually this is what I really want:
progressbar will alway be the fist line,and got a response,then show it at below.
anyway to fix that?
Nodejs:
var request = require('request');
var ProgressBar = require('progress');
var year=[14,15,16];
var month=[1,2,3,4,5,6,7];
var bar = new ProgressBar('Processing [:bar] :percent', {
complete: '=',
incomplete: '-',
width: 30,
total: year.length*month.length,
});
/*-------------------------------------*/
function init(year,month){
check(year,month);
}
function check(year,month){
var options = { method: 'POST',
url: 'http://dev.site/date.php',
formData:{year:year,month:month}
};
request(options, function (error, response, body) {
if (error) {
console.log(error);;
}
if (body=='A task #') {
bar.tick();
console.log('\n'+body+year+':'+month);
}else{
bar.tick();
}
})
}
/*-------------------------------------*/
for (var i = 0; i < year.length; i++) {
for (var n = 0; n < month.length; n++) {
init(year[i],month[n]);
}
}
Using ansi-escapes you may be able to do this.
Here's a standalone version:
const ProgressBar = require('progress');
const ansiEscapes = require('ansi-escapes');
const write = process.stdout.write.bind(process.stdout);
let bar = new ProgressBar('Processing [:bar] :percent', {
complete : '=',
incomplete : '-',
width : 30,
total : 100
});
// Start by clearing the screen and positioning the cursor on the second line
// (because the progress bar will be positioned on the first line)
write(ansiEscapes.clearScreen + ansiEscapes.cursorTo(0, 1));
let i = 0;
setInterval(() => {
// Save cursor position and move it to the top left corner.
write(ansiEscapes.cursorSavePosition + ansiEscapes.cursorTo(0, 0));
// Update the progress bar.
bar.tick();
// Restore the cursor position.
write(ansiEscapes.cursorRestorePosition);
// Write a message every 10 ticks.
if (++i % 10 === 0) {
console.log('Now at', i);
}
// We're done.
if (i === 100) {
process.exit(0);
}
}, 100);
I use pixi.js v 3.0.0
My simple code is
(function () {
document.addEventListener('DOMContentLoaded', function () {
var width = screen.availWidth;
var height = screen.availHeight;
var renderer = PIXI.CanvasRenderer(width, height, {
backgroundColor : 0x1099bb
});
document.body.appendChild(renderer.view);
var stage = new PIXI.Container();
var texture = PIXI.Texture.fromImage('asset/bunny.png');
var bunny = new PIXI.Sprite(texture);
bunny.anchor.x = 0.5;
bunny.anchor.y = 0.5;
bunny.position.x = 200;
bunny.position.y = 150;
stage.addChild(bunny);
animate();
function animate() {
requestAnimationFrame(animate);
bunny.rotation += 0.1;
renderer.render(stage);
}
}, false);
}
());
But i get: TypeError: this.initPlugins is not a function if use CanvasRenderer but it works in other cases
Just add new keyword when creating the CanvasRenderer.
I am creating a Chrome Extension that would draw an image above tag showing Flash content. I have written the content script in my "contentscript.js" file which does nothing but simply inserts another script file "backgroundscript.js" into page's body via a script tag.
The code works on few of sites having flash videos and shows the image right above the Flash Player window but on other sites it does not show up. Also on few it shows up for a fraction of a second and then gets disappeared.
Below is my manifest file:
{
"name": "My First Chrome Extension",
"version": "1.0.0.0",
"description": "Tag videos from websites with a single click!",
"icons": { "16":"application_16.png","48":"application_48.png","128":"application_128.png" },
"homepage_url": "http://www.myurl.com",
"page_action":{
"default_icon":{
"19":"application_19.png",
"38":"application_38.png"
},
"default_title":"VDownloader browser plugin"
},
"content_scripts": [ { "js": [ "contentscript.js" ], "matches": [ "http://*/*" ], "run_at" : "document_end", "all_frames": true} ],
"plugins": [ { "path": "myplugin.dll", "public": true } ],
"manifest_version":2,
"minimum_chrome_version":"17",
"offline_enabled":true,
"permissions":["tabs","http://*/*", "https://*/*","contextMenus"],
"web_accessible_resources":["application.png","backgroundscript.js"]
}
Also I checked by inserting "debugger;" into my script and monitoring code execution via console; the script gets added at least once into the page body. Even in the cases where no image button is shown.
Is this some kind of anit-XSS control implemented on the the more advanced sites not showing my button?
I would really appreciate your help as I have been trying to get over this from past couple of weeks without success :(
EDIT:
Please see the content script below:
var s = document.createElement('script');
s.src = chrome.extension.getURL("backgroundscript.js");
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
Target sites:
Does not show the button: http://www.metacafe.com
Shows the button for a moment: http://www.dailymotion.com
Shows the button correctly: http://www.myreviewalarm.com
Please take a look at backgroundscript.js content:
var vdDelayTimer;
var vdUpdateInterval;
var playerButtons;
embedPlugin();
function embedPlugin() {
var embed = document.createElement('embed');
embed.setAttribute('type', 'application/x-myplugin');
embed.setAttribute('id', 'myplugin');
embed.setAttribute('style', 'width:1px;height:1px;position:absolute;left:0px;top:0px;');
if(document.body!=null)
{
document.body.appendChild(embed);
}
testPlugin();
}
function testPlugin() {
var plugin = document.getElementById('vdPlugin');
if (plugin != null) {
playerButtons = [];
vdDelayTimer = setTimeout("appendButtons()", 2000);
}
else {
window.alert('Plugin does not exist!');
}
}
function updateButtons() {
for (i = 0; i < playerButtons.length; i += 2) {
updateButtonLocation(playerButtons[i], playerButtons[i + 1]);
}
}
function updateButtonLocation(player, button) {
var playerX = getX(player);
var playerY = getY(player);
var buttonHeight = 38;
var buttonWidth = 196;
var buttonX = playerX + player.offsetWidth - buttonWidth - 12;
var buttonY = playerY - buttonHeight + 1;
button.setAttribute('style', 'background-image: url(http://myurl.com/img/browser-download-button.png); width:' + buttonWidth + 'px;height:' + buttonHeight + 'px;position:absolute;left:' + buttonX + 'px;top:' + buttonY + 'px; cursor:pointer; cursor:hand;');
}
function appendButtons() {
debugger;
var objectTags = document.getElementsByTagName('object');
for (var i = 0; i < objectTags.length; i++) {
var objectTag = objectTags[i];
if ((objectTag.hasAttribute('classid') && objectTag.getAttribute('classid') == 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000')
|| (objectTag.hasAttribute('type') && objectTag.getAttribute('type') == 'application/x-shockwave-flash')) {
if (objectTag.offsetWidth >= 320 && objectTag.offsetHeight >= 240)
createButton(objectTag, getX(objectTag), getY(objectTag), objectTag.offsetWidth);
}
}
var embedTags = document.getElementsByTagName('embed');
for (var i = 0; i < embedTags.length; i++) {
try {
var embedTag = embedTags[i];
if (embedTag.hasAttribute('type') && embedTag.getAttribute('type') == 'application/x-shockwave-flash') {
if (embedTag.offsetWidth >= 320 && embedTag.offsetHeight >= 240)
createButton(embedTag, getX(embedTag), getY(embedTag), embedTag.offsetWidth);
}
}
catch (err) { }
}
var videoTags = document.getElementsByTagName('video');
for (var i = 0; i < videoTags.length; i++) {
try {
var videoTag = videoTags[i];
if (videoTag.hasAttribute('src')) {
if (videoTag.offsetWidth >= 320 && videoTag.offsetHeight >= 240)
createButton(videoTag, getX(videoTag), getY(videoTag), videoTag.offsetWidth);
}
}
catch (err) { }
}
vdUpdateInterval = setInterval("updateButtons();", 500);
}
function createButton(videoTag, playerX, playerY, playerWidth) {
debugger;
var buttonHeight = 38;
var buttonWidth = 196;
var buttonX = playerX + playerWidth - buttonWidth - 12;
var buttonY = playerY - buttonHeight + 1;
var vdPlugin = document.getElementById('vdPlugin');
var strLocation = window.location.toString();
// if (isSupported(strLocation)) {
var downloadButton = document.createElement('img');
downloadButton.setAttribute('title', 'Tag this video');
downloadButton.setAttribute('src', 'http://myurl.com/img/browser-download-button.png');
downloadButton.setAttribute('style', 'background-image: url(http://myurl.com/img/browser-download-button.png); width:' + buttonWidth + 'px;height:' + buttonHeight + 'px;position:absolute;left:' + buttonX + 'px;top:' + buttonY + 'px; cursor:pointer;cursor:hand;z-index:2147483647;');
downloadButton.setAttribute('onclick', 'javascript:document.getElementById(\'vdPlugin\').downloadNow(window.location.href);');
downloadButton.setAttribute('oncontextmenu', 'javascript:return false;');
document.body.appendChild(downloadButton);
playerButtons.push(videoTag, downloadButton);
// }
}
function getY(oElement) {
var iReturnValue = 0;
while (oElement != null) {
iReturnValue += oElement.offsetTop;
oElement = oElement.offsetParent;
}
return iReturnValue;
}
function getX(oElement) {
var iReturnValue = 0;
while (oElement != null) {
iReturnValue += oElement.offsetLeft;
oElement = oElement.offsetParent;
}
return iReturnValue;
}
function isSupported(url) {
var regLen = supportedSites.length;
var regEx;
var res = false;
try {
for (var i = 0; i < regLen && res == false; i++) {
regEx = new RegExp(supportedSites[i], "i");
res = regEx.test(url);
}
}
catch (ex) {
}
return res;
}