How can I change a number in a time interval with Cocos2d Javascript engine?
With pure js I could use setInterval, but does any function in the cocos2d library do it?
You didn't write any code so I'll be using the one posted here.
To display a number in the center of the screen, that increases every second, I'd add this to MainLayer.js:
var MainLayer = cc.LayerColor.extend({
_labelNumber:null,
_number:0,
_updateRate:1.0,
onEnter:function () {
_number = 0;
var labelName = ""+_number;
_labelNumber = cc.LabelTTF.create(labelName, "Arial", 32);
_labelNumber.setColor(cc.c3(64, 64, 64));
_labelNumber.setPosition(winSize.width/2, winSize.height/2);
_updateRate = 1.0;
this.addChild(_labelNumber);
this.schedule(this.updateNumber, _updateRate);
},
updateNumber:function() {
_number++;
if(_labelNumber == null) return;
_labelNumber.setString(""+_number);
}
});
Related
How I can make it work accurately so that each picture is exactly shown 50ms after the last one? (And so that the calculated time between seeing the picture and clicking is accurate?)
Background
I want to have a slideshow of images. The images are stored in the images directory and their names are sequential. The slideshow should start after the user clicks on the play button. And the user will click on the stop button a little after the 100th picture. And the code will show the user how many milliseconds after seeing the 100th picture they have clicked on the stop button. The problem is that when I run the code it doesn't work so accurate. It has some lag on some pictures. I was wondering
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var player;
var timestamp;
function preloadImage()
{
var i = 1
while(true){
var img = new Image();
img.src="images/" + i;
i = i + 1;
if (img.height == 0) { break; }
}
}
function next(){
var fullPath=document.getElementById("image").src;
var filename = fullPath.split("/").pop();
var n=parseInt(filename, 10) + 1;
document.getElementById("image").src = "images/" + n;
if (document.getElementById("image").height == 0) { clearInterval(player); }
if (n == 100) { timestamp = new Date().getTime(); }
}
function start(){
clearInterval(player);
document.getElementById("image").src = "images/1";
player = setInterval(function(){ next(); }, 50)
}
function stop(){
clearInterval(player);
alert("You clicked after " + (new Date().getTime() - timestamp) + "ms.")
}
preloadImage()
</script>
</head>
<body>
<img src="images/0" id="image"><br/>
<button type="button" onclick='start()'>start</button>
<button type="button" onclick='stop()'>stop</button>
</body>
</html>
As I stated in my comment, I believe your preloadImage() is not working as you expect. Try running the stack snippet below as a demonstration, and possibly make sure your cache is cleared:
function badPreloadImage () {
var img = new Image();
img.onload = function () {
// check it asynchronously
console.log('good', this.height);
};
img.src = 'https://www.w3schools.com/w3css/img_lights.jpg';
// don't check height synchronously
console.log('bad', img.height);
}
badPreloadImage();
To preload all your images properly, you must do so asynchronously:
function preloadImage (done, i) {
if (!i) { i = 1; }
var img = new Image();
img.onloadend = function () {
if (this.height == 0) { return done(); }
preloadImage(done, i + 1);
};
img.src = "images/" + i;
}
// usage
preloadImage(function () { console.log('images loaded'); });
Other concerns
You should consider using performance.now() instead of new Date().getTime(), as it uses a more precise time resolution (currently 20us, as pointed out in this comment).
You might also consider storing references to each image as an array of Image objects, rather than loading each frame via specifying the src property of an HTMLImageElement, so that the browser can just load the data from memory, rather than loading from cache on the hard drive, or even making a new HTTP request when caching is not enabled.
Addressing each of these issues will allow you to measure timing more precisely by using the proper API and eliminating lag spikes on the DOM thread due to inefficient animation.
I have the following two pieces of code (awful but I have no idea what I'm doing):
var stage = new createjs.Stage("canvas");
createjs.Ticker.on("tick", tick);
// Simple loading for demo purposes.
var image = document.createElement("img");
image.src = "http://dossierindustries.co/wp-content/uploads/2017/07/DossierIndustries_Cactus-e1499205396119.png";
var _obstacle = new createjs.Bitmap(image);
setInterval(clone, 1000);
function clone() {
var bmp = _obstacle.clone();
bmp.x= Math.floor((Math.random() * 1920) + 1);
bmp.y = Math.floor((Math.random() * 1080) + 1);
stage.addChild(bmp);
}
function tick(event) {
stage.update(event);
}
<script>
$j=jQuery.noConflict();
jQuery(document).ready(function($){
var interval = 1;
setInterval(function(){
if(interval == 3){
$('canvas').show();
interval = 1;
}
interval = interval+1;
console.log(interval);
},1000);
$(document).bind('mousemove keypress', function() {
$('canvas').hide();
interval = 1;
});
});
<script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>
<canvas id="canvas" width="1920" height="1080"></canvas>
Basically what I'm hoping to achieve is that when a user is inactive for x amount of time the full page (no matter on size) slowly fills with the repeated image. When anything happens they all clear and it begins again after the set amount of inactivity.
The code above relies on an external resource which I'd like to avoid and needs to work on Wordpress.
Site is viewable at dossierindustries.co
Rather than interpret your code, I made a quick demo showing how I might approach this.
The big difference is that drawing new images over time is going to add up (they have to get rendered every frame), so this approach uses a cached container with one child, and each tick it just adds more to the cache (similar to the "updateCache" demo in GitHub.
Here is the fiddle.
http://jsfiddle.net/dcs5zebm/
Key pieces:
// Move the contents each tick, and update the cache
shape.x = Math.random() * stage.canvas.width;
shape.y = Math.random() * stage.canvas.height;
container.updateCache("source-over");
// Only do it when idle
function tick(event) {
if (idle) { addImage(); }
stage.update(event);
}
// Use a timeout to determine when idle. Clear it when the mouse moves.
var idle = false;
document.body.addEventListener("mousemove", resetIdle);
function resetIdle() {
clearTimeout(this.timeout);
container.visible = false;
idle = false;
this.timeout = setTimeout(goIdle, TIMEOUT);
}
resetIdle();
function goIdle() {
idle = true;
container.cache(0, 0, stage.canvas.width, stage.canvas.height);
container.visible = true;
}
Caching the container means this runs the same speed forever (no overhead), but you still have control over the rest of the stage (instead of just turning off auto-clear). If you have more complicated requirements, you can get fancier -- but this basically does what you want I think.
We are working on visualization of sorting algorithms, required to add sleep and wait logic to help visualize the selected element and the element to which it is compared. After searching li'l bit, we found a code "function sleep(milliseconds){...}" which should work as desired but has failed so far.
In function insertionSort(){...}, the current element is depicted with color red and the element to which it is compared with is depicted with color blue, once the current element is swapped with the other the color of the element is again changed to white from blue (working correctly, verified using debugger), However during execution, these color transformations were not visible (only the element in red is displayed after each iteration)
var element = function(value, color)
{
this.value = value;
this.color = color;
};
var x = [];
x[0] = new element(2, "white");
x[1] = new element(1, "white");
x[2] = new element(5, "white");
x[3] = new element(4, "white");
x[4] = new element(3, "white");
x[5] = new element(7, "white");
x[6] = new element(6, "white");
x[7] = new element(8, "white");
x[8] = new element(10, "white");
x[9] = new element(9, "white");
var i = 1;
var context;
var delayTime = 1000;
function myFunction()
{
var bar = document.getElementById("bar");
width = bar.width;
height = bar.height;
context = bar.getContext("2d");
window.setInterval(insertionSort, 3000);
}
function insertionSort()
{
if(i>=0 && i<x.length)
{
var j = i;
x[j].color = "red";
drawGraph(j);
while(j>0 && x[j-1].value > x[j].value)
{
x[j-1].color = "blue";
x[j].color = "red";
drawGraph();
//need to add delay here
sleep(delayTime);
//swap
var temp = x[j];
x[j] = x[j-1];
x[j-1] = temp;
drawGraph();
// and here...
sleep(delayTime);
x[j].color = "white";
drawGraph();
j = j-1;
}
x[j].color = "white";
i++;
}
else if(i>=x.length)
{
for(k=0;k<x.length;k++)
{
x[k].color = "white";
}
drawGraph();
i=-1;
}
}
function sleep(milliseconds)
{
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++)
{
if ((new Date().getTime() - start) > milliseconds)
{
break;
}
}
}
function drawGraph()
{
context.StrokeStyle = "black";
context.clearRect ( 0 , 0 , width, height);
for(k=0;k<x.length;k++)
{
context.fillStyle = x[k].color;
//x and y coordinate of top left corner of rectangle
context.strokeRect(400+k*20, 18, 20, x[k].value*10);
context.fillRect(400+k*20, 18, 20, x[k].value*10);
}
}
<html>
<head>
<script language="javascript" type="text/javascript" src="../p5.js"></script>
<!-- uncomment lines below to include extra p5 libraries -->
<!--<script language="javascript" src="../addons/p5.dom.js"></script>-->
<!--<script language="javascript" src="../addons/p5.sound.js"></script>-->
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<!-- this line removes any default padding and style. you might only need one of these values set. -->
<style> body {padding: 0; margin: 0;} </style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<canvas id="bar" width="1000" height="400" style="border:2px"></canvas>
</body>
</html>
The approach to used in that implementation of sleep() would be terrible in any programming language, because it consumes a lot of CPU while waiting. In JavaScript, however, it's especially bad, because a JavaScript program is required to relinquish control frequently; it is not permitted to keep computing for an extended period of time. In Chrome browser, for example, Chrome will consider the program to be unresponsive, and will suggest to the user that they kill it.
But even if that weren't the case, it won't produce the desired effect, which I assume is that some animation happens on the screen, with some delay from one step to the next. The way JavaScript works in the browser, is that any changes you make to the page get rendered when your program relinquishes control; nothing updated on-screen while any JavaScript code is running. If you call a sleep function like that one, you are not relinquishing control, you are running JavaScript the whole time, and therefore the browser will not update the screen during that time. It will only update when your entire insertionSort method returns, and the browser has that 3000ms time window (from your setInterval) to take care of its own stuff (rendering).
Unfortunately, you will have to find a way to split up that algorithm, so that each step that you want to be distinctly visible to the user happens in its own timed callback.
It will probably be something along the lines of:
function stepOne() {
do the first bit;
setTimeout(secondStep, delay)
}
secondStep() {
do some more stuff;
setTimeout(thirdStep, delay)
}
and so on. The way you control the speed of the animation is with the delay parameter from one step to the next.
It's going to be tricky, especially because you aren't just trying to animate Insertion Sort, but various algorithms. So then, do you break them all up as in: insertionSortStepOne/Two/Three, shellSortStepOne/Two/Three? that would be quite ugly.
Depending on how ambitious you are, and how much you want to get out of this assignment, you might explore this feature of ES6 (a newer version of JavaScript)
function*
What this lets you do is let your function, with all its nested loops, remain structured pretty much as it is, but you insert points where it relinquishes control. Later, it is called back to continue from the point where it left off. You would use setTimeout or setInterval to do that. I've not experimented with this myself, but it seems super-cool.
I'm new on learning javascript. I'm working on my school project and I faced some problems. I want to create a countdown timer and also display it out indicating "3,2,1...". Creating this for a photo capturing system by using HTML5 and JS.
When user click on the button that said CAPTURE, there will be a line of word written down "Photo will be captured in (3,2,1)". Then call the function below.
context.drawImage(video, 0, 0, 640, 480);
I know can done by using
setTimeout(function(){context.drawImage(video, 0, 0, 640, 480)},3000);
but I don't know how to link it with the button that written "CAPTURE", and display the indicator by saying 3, 2, and then 1.
sorry for the poor english that I wrote.
Try following code
var currectValue = 0;
var timer = -1;
function onTimer(){
if(currentValue == 0){
clearTimeout(timer);
return;
}
currentValue -= 1;
//Your code
}
function startCountdown(seedValue){
currentValue = seedValue;
if(-1 != timer){
clearTimeout(timer);
timer = -1;
}
timer = setInterval(onTimer, 1000);
}
startCountdown(3);
Try this example,
function timer(object){
if(object==0)
context.drawImage(video, 0, 0, 640, 480);
else{
object = object -1;
setTimeout("timer('"+object+"')",1000);
}
}
Externally call like onclick="timer(3)"
I'm trying to get a script to run but I'm having a little trouble. I've only used javascript once before, but now i have to make a character animation walk back and forth on a web page and continue until the page is closed. My debugger says there is a reference error on line 57, but i'm sure thats not the only problem. If anyone could take a look at the code and see if anything pops out at them, I would be grateful.
goog.provide('mysprites');
goog.require('lime');
goog.require('lime.Director');
goog.require('lime.Layer');
goog.require('lime.Sprite');
goog.require('lime.fill.Frame');
goog.require('lime.animation.KeyframeAnimation');
goog.require('lime.animation.MoveBy');
goog.require('lime.SpriteSheet');
goog.require('lime.animation.MoveTo');
goog.require('lime.animation.Sequence');
goog.require('lime.animation.Loop');
goog.require('lime.animation.Delay');
goog.require('lime.parser.JSON');
goog.require('lime.ASSETS.spaceman.json');
mysprites.WIDTH = 600;
mysprites.HEIGHT = 400;
mysprites.start = function() {
//director
mysprites.director = new lime.Director(document.body, mysprites.WIDTH, mysprites.HEIGHT);
mysprites.director.makeMobileWebAppCapable();
var gamescene = new lime.Scene;
layer = new lime.Layer();
gamescene.appendChild(layer);
// load the spritesheet
mysprites.ss = new lime.SpriteSheet('assets/spaceman.png',lime.ASSETS.spaceman.json,lime.parser.JSON);
var sprite = mysprites.makeMonster().setPosition(100,100);
layer.appendChild(sprite);
//move
var moveRight = new lime.animation.MoveTo(874, 100)
.setSpeed(1)
.setEasing(lime.animation.Easing.LINEAR);
var moveLeft = new lime.animation.MoveTo(100, 100)
.setSpeed(1)
.setEasing(lime.animation.Easing.LINEAR);
// show animation
var anim = new lime.animation.KeyframeAnimation();
anim.delay= 1/10;
for(var i=0;i<=9;i++){
anim.addFrame(mysprites.ss.getFrame('spaceman-'+'w'+'0'+i+'.png'));
}
monster.runAction(anim);
var anim2 = new lime.animation.KeyframeAnimation();
anim.delay= 1/10;
for(var i=0;i<=9;i++){
anim.addFrame(mysprites.ss.getFrame('spaceman-'+'e'+'0'+i+'.png'));
}
monster.runAction(anim2);
goog.events.listen(moveRight,lime.animation.Event.STOP, function () {
setTimeout(function () {
monster.runAction(moveLeft);
}, 500);
});
goog.events.listen(moveLeft,lime.animation.Event.STOP, function () {
setTimeout(function () {
monster.runAction(moveRight);
}, 500);
});
};
mysprites.makeMonster = function(){
var sprite = new lime.Sprite().setPosition(200,200)
.setFill(mysprites.ss.getFrame('spaceman-s00.png'));
//layer.appendChild(sprite);
return sprite;
};
goog.exportSymbol('mysprites.start', mysprites.start);
I think you'd better to ask your question here https://groups.google.com/forum/#!forum/limejs
Please check the following things:
If all the spritesheet items referenced in KeyframeAnimation are present in your spritesheet
Try to use setDelay, setLooping API methods instead of direct assignment
I do not see monster variable definition...