I need to draw fractal using js turtle library so, the fractal is animated until it is drawn totally like the python turtle example here
I've tried in the command here. There's a function called animate in the docs but I'm not able to use it, it only waits for some time then draw the fractal without any animation.
I type in the command input animate(demo, 1000)
Is there any suggestion?
if I can't use animation in js turtle Is there another fast easy library that can do the job of drawing fractals?!
You're not using animate() correctly. You can't just apply it to a finished program and expect its behavior to change. Instead, you need to incorporate it into the program. There should be a function that draws a portion of the animation each time it's called. Then have it called over and over by animate(). Rewritting your example:
function square(side) {
repeat(4, function () {
forward(side);
right(90);
});
}
var s = 100
function draw() {
square(s);
right(36)
s -= 10
if (s < 0) {
s = 100
clear()
}
}
function demo() {
hideTurtle();
colour(0, 0, 255, 1);
animate(draw, 500);
}
Invoke it via demo(), don't call animate() on it. It's basic animation unit is the square. If you want to see the squares being drawn, then you need to redesign the code to make the basic animation unit the side of a square (i.e. line.)
Related
I have a piece of javascript that I have copied & edited, that is designed for an animated loading ring but the animation only runs once, I would like it to run every 4 seconds, until the page is loaded, but I can't find the right syntax/script to get it to repeat, i do not want it to reload the page only loop that specific script until i set it to stop.
".radial" is the class of the radials contained inside my css & html files.
there is twelve of them & they do-not rotate only the fluorescent .glow animation part makes it appear as they are rotating. the code is;
const radials = [...document.querySelectorAll('.radial')];
let degrees = 29;
for(i=0; i < radials.length; i++) {
degrees += 13;
radials[i].style.transform = `rotate(${degrees}deg)`;
degrees += 34;
}
radials.forEach((radial, index) => {
setTimeout(function() {
radial.classList.add('glow');
},index * 29);
});
:: Update ::
Having read the comments below and searching on Youtube. I think that wrapping the whole script in a function, would be the best option. Including a call to that function within its self & passing it an argument in the parenthesis of a timeout or delay property. But setInterval() & setTimeOut() both use the unsafe eval() function underneath. Which is supposed to be a security concern.
Also a youtube video I watch a while ago, said that setInterval() & setTimeOut() do not achieve 60fps. requestAnimationFrame() Would be A much better option. I'm not sure how legitamate these claims are, or where his sources were from but I will continue searching the Webs.
The glow part looks good but I just haven't been able to get it to repeat.
I am new to Js please be patient.
is there any other workarounds for the setTimeOut() & setInterval().?
Place this code into a function that is passed to a setInterval() timer call.
function loop() {
const radials = [...document.querySelectorAll('.radial')];
let degrees = 29;
for(i=0; i < radials.length; i++) {
degrees += 13;
radials[i].style.transform = `rotate(${degrees}deg)`;
degrees += 34;
}
radials.forEach((radial, index) => {
setTimeout(function() {
radial.classList.add('glow');
},index * 29);
});
setTimeout(loop, 4000);
}
Use setInterval(). The setInterval takes two parameters, the first is the function you want to run and the second is your repeat time in miliseconds. So to run a function every 4 seconds you would do:
setInterval(function() {
// do something
}, 4000);
You can do it with setInterval, as in the other answers, but I think that the logic is clearer if you have an animate function that keeps calling itself.
You are adding a "glow" class, but you are never removing it. The animate function should toggle it on and off. To make it crystal clear, let's make that a separate function, toggleGlow.
Next, each animation loop we kick off the individual toggleGlow functions with a different delay for each radial.
Finally, the animate function will re-call itself after a short, constant, delay each time, until some stop condition is met (like the page loading).
const radials = [...document.querySelectorAll('.radial')];
function toggleGlow(element) {
if (element.classList.contains("glow")) {
element.classList.remove("glow");
} else {
element.classList.add("glow");
}
}
function animate() {
radials.forEach((radial, index) => {
setTimeout(function() {
toggleGlow(radial);
}, index * 29);
});
if (!stopCondition) {
setTimeout(animate, 200);
}
}
// kick it off
animate();
JSFiddle example here: https://jsfiddle.net/duxhy3Lj/
I'm getting into game developing online. I am trying to make an online FPS game, and I've only gotten to the point where I need to update my character. I am trying to keep my code simple, using only a draw and update function. When the html loads, I execute both: (Is this necessary?)
<body onload='DRAW(); UPDATE();'>
The draw function draws the player to the screen, and the update is supposed to check for a keypress to move the character. I am trying to make the script update using this:
function UPDATE()
{
update = setInterval(UPDATE, 60);
}
and to my knowledge, it is working fine because when I try and edit code in my online IDE (c9.io) which I use to test the site, it freezes when the site is running. I am also calling eventListeners in the draw function. (Is this proper if I want to test for a key down every frame?)
function DRAW()
{
window.addEventListener('keydown', function (e) {
keys.keys = (keys.keys || []);
keys.keys[e.keyCode] = true;
});
window.addEventListener('keyup', function (e){
keys.keys[e.keyCode] = false;
});
}
My questions are:
Is there an easier way to make a script update every frame?
Is there a JavaScript addon (like Three.js) I can use to make
developing this easier on myself?
Any knowledge is greatly appreciated.
This makes everything crash:
function UPDATE()
{
update = setInterval(UPDATE, 60);
}
You are recursively creating a new interval every 60ms; the first time you call UPDATE, you create an interval that creates a new interval every 60ms. All newly create intervals do the same. Don't really know what you actually want to do here.
I am also calling eventListeners in the draw function. (Is this proper
if I want to test for a key down every frame?)
It's fine to create eventlisteners in the draw function, provided you only call this function once. Which I guess you don't. Each time you call DRAW() a new set of eventlisteners will be added, and you really don't want that.
What you need is a form of game loop. Explaining how to create an FPS game is a bit more than I can do, but you can start by looking at this article Anatomy of a video game
I am writing some motor controls with node.js using cylon.js. I have a servo, which when you give it an angle to go to has a callback function. When it finishes that function, I want to do another reading, and give it a new angle, with the callback to do another reading...so forth and so on.
the current code is:
function ControlServo(servo, angleSensor){
robo.servo.angle(angleSensor.Read(), controlServo(servo, angleSensor));
}
That gets stack overflowed in like a quarter second.
It's not possible to do what you want to do with Cylon.js. Cylon.js's internal "write" operation "callback" is not async and doesn't get called when the move is mechanically completed. It gets called immediately after the write operation. Cylon can only write the angle value to the servo, which mechanically moves the horn at its max capable speed. If it's a slow servo, it could take 2 whole seconds from 0 to 180 degrees before it's actually mechanically complete. In the meantime, Cylon has already called the callback. The reason for this is because there is no way to generalize that callback behavior in a way that would be consistently correct for all servo models, without doing a little extra work.
In Johnny-Five we've implemented speed control that's enabled by providing a "time to complete" argument. This is done by dividing the distance to the new angle into steps to move in the specified "time to complete". A side effect of this process is that Johnny-Five servo instances can know when the move is mechanically complete, because the steps are smaller and the timing controlled. As a result, we have a "move:complete" event that emits when any timed move is completed.
var servo = new five.Servo(9);
servo.on("move:complete", function() {
// we've arrived!
});
// change takes 500ms to complete
servo.to(180, 500);
That can easily be combined with an analog sensor:
var servo = new five.Servo(9);
var sensor = new five.Sensor({
pin: "A0", scale: [ 0, 180 ]
});
servo.on("move:complete", function() {
update();
});
function update() {
// change takes 200ms to complete
servo.to(sensor.value, 200);
}
update();
Even simpler:
var servo = new five.Servo(9);
var sensor = new five.Sensor("A0");
sensor.scale(0, 180).on("change", function() {
servo.to(this.value);
});
A better way to solve this is using a timeout instead of recursing. This ends up calling your function on the next tick, which will never overflow.
function ControlServo(servo, angleSensor){
robo.servo.angle(angleSensor.Read(), function() {
setTimeout(function() { ControlServo(servo, angleSensor)}, 0);
});
};
You could shorten this by moving the timeout into the servo.angle function, but you might need it to be a callback for other uses. The method above requires no other change, since the callback is just setting the timeout.
Another option is setImmediate, which appears to put the function call at the end of the current tick, instead of the beginning of the next one. Since setTimeout will always introduce a slight delay, setImmediate might be faster; however, I don't know what other tradeoffs might be made using this as I haven't used it much myself.
Is possible to translate in Javascript the auto-recall function draw() in Processing? How to simulate that behavior in JS?
There isn't a way Javascript on its own but if you download jQuery (https://jquery.com/) you are able to do something that works very similarly to the draw function in processing.
By using a piece of code similar to this you should be able to get a pretty good result:
setInterval(function() {
draw();
}, 1); //So it waits one millisecond untill calling the draw function
function draw() {
//Your code goes in here
}
I hope this works for you!
I know this question has been asked a lot of times, and I have seen the solutions to them on SO as well as other forums. Most of the times the solution suggested is to use Web Workers.
A game I'm developing requires me to run multiple functions at the same time. One of them is an on click function and other is a setInterval.
My approach at doing this can be seen here in this JSFiddle. (keep clicking in gray area to make player jump).
The whole idea is to continuously spawn those blue obstacles after an interval of 1000ms.
In my earlier approach the obstacles would spawn only when I click to make player jump, otherwise they wouldn't as expected.
How can I run such two functions side by side in order to achieve
the aim of spawning obstacles while also making player jump.
Secondly, what would be the best approach to carry out this process
in view of game development i.e attaining a certain level of
efficiency so that the animations are not affected.
Here is the HTML and Javascript code I've been working on:
<div class="container">
<div class="player"></div>
<div class="obstacle-container">
<div class="obstacle"></div>
</div>
</div>
$.fn.animator = function () {
var hit_list, done = false;
$(".container").click(function () {
if (!done) {
$(".obstacle").stop().animate({
left: "-=105%"
}, 10000, "linear");
$(".player").stop().animate({
bottom: "+=100px"
}, {
duration: 300,
complete: function () {
$(".player").animate({
bottom: "0"
}, 800);
},
step: function () {
//Test for collision
hit_list = $(".player").collision(".obstacle");
if (hit_list.length !== 0) {
$(function () {
if (!done) {
$(".container").append("Game Over!");
return false;
}
});
done = true;
}
}
});
}
});
};
$(function () {
$('.container').animator();
});
var interval = null;
$(".obstacle-container").obstacle_generator();
$.fn.obstacle_generator = function () {
interval = setInterval(function () {
$(".obstacle-container").append('<div class="obstacle"></div>');
}, 1000);
};
The generic concept you want to investigate is known as a game loop.
Almost every game will be built using some variant of this system:
Initialise game
Loop:
Check for user input
Update any actors
Draw the scene
Wait until it's time to repeat
A game running at 60 frames per second would perform this loop 60 times per second, or about once every 16ms.
Compared to your original question, you wouldn't need to be running multiple execution threads (running multiple functions together) to achieve this.
You are, in a way, already using a similar loop. jQuery maintains its own loop for updating animations. Where you are checking for collisions as part of your animation step, this is the sort of thing you would do in a hypothetical Player.update() method. You want to move this code out of jQuery, and in to a loop that you control.
Since you're running in a browser, the generic game loop becomes a bit more simple:
Check for user input - this can still be handled by event handlers, jQuery or not. Rather than directly changing properties like CSS position, though, they should act upon the state of the game object. For example, by changing the velocity of a Player object.
Update any actors - the important part of your loop. You should check how many milliseconds have passed since you last looped, since the browser doesn't guarantee that your code will be run exactly, or at least, 60 times per second. You should then loop through all of your game objects and update them all. In your Player.update() method, you would want to move it according to its velocity and the time passed, for example.
Draw the scene - if you're using DOM elements, then the browser handles drawing for you, of course. If you were using a <canvas> element, then you would do drawing yourself as part of the loop here.
Wait until it's time to repeat - this will be up to the browser to do for you, as part of normal setInterval/setTimeout behavior.
A simple game loop in JavaScript can look like this:
var gameObjects = [];
// Initialise game, create player objects etc, add them to the array
var gameLoop = function() {
// Loop through gameObjects, and call their respective update methods
};
setInterval(gameLoop, 16); // Try to run the loop 60 times per second.
In a complex game, you wouldn't have just a basic array to hold all game objects, this is just an basic example.