Timed jQuery rotation - javascript

I'm trying to make the selector rotate at varying times, I figured I would try a simple if/else statement, to make the first one rotate after 3 seconds, and the following ones after 30 seconds. However, it just keeps rotating it every three seconds. Had I figured how to make this work, I was planning on adding more if/else statements inside the previous one, so that I could add custom times for each slide. Any ideas how I could achieve this?
$(document).ready(function(){
var flipped = false;
if (!flipped)
{
$('#Blog1 > ul').tabs({fx:{opacity: 'toggle'}});
$('#Blog1 > ul').tabs('rotate', 3000, true);
flipped = true;
}
else
{
$('#Blog1 > ul').tabs({fx:{opacity: 'toggle'}});
$('#Blog1 > ul').tabs('rotate', 30000, true);
}
});

You're clearly setting "flipped" to false every time you run the function.
Or rather, your not running it again to check for flipped. (I think)
You need to separate the variable from the function, otherwise it will always be false.
As for time, you can easily use Math.random()
randomNumber = Math.floor((Math.random() * 30) + 1); // Random number between 1 and 30
$('#Blog1 > ul').tabs({fx:{opacity: 'toggle'}});
$('#Blog1 > ul').tabs('rotate', randomNumber, true);

Related

How to limit the amount of bullets in a JavaScript Game?

So the question is really bad because I don't know what to ask or call what I'm trying to do, but...
I have a game I'm creating and I've added in an array for the lasers. It works fine but I want to limit the number of lasers that can be on the screen at once so the player doesn't just spam the space bar to win.
I tried limiting it by making a set number of bullets which only allows the user to shoot twice but where I tried to add back bullets once it reached the top of the canvas so they could start shooting again but it didn't work.
I assume this is because it is within the spacePressed if and so it considers spacePressed to be false so it won't run where it adds one bullet but when I put the adding bullets if outside the spacePressed it still didn't work.
I'm not sure how to go about doing what I'm trying to do and would appreciate any ideas towards fixing this. I will also have to add in later where the laser disappears upon hitting the meteor and adds back one bullet so I would also like help with figuring that out.
https://jsfiddle.net/200uaqrn/18/ <-before adding any bullets
https://jsfiddle.net/200uaqrn/19/ <-adding in my attempt to create limited bullets
if(spacePressed) {
if(lasers.y<=laserSize) {
bullets+=1;
}
else{
drawLaser();
lasers.forEach(function(laser,index){
laser.y-=laserdY;
})
}
}
Also separate question for the same project I'm going to later make multiple meteors falling at once and I assume I would use an array for that. But I don't know how to use that array to make them fall from random y cords at different times, etc.
For the laser, you can try to just set a function with timeout:
var canFire = true;
function allowFire() {
canFire = true;
}
function newLaser() {
this.x = turretX
this.y = canvas.height - 75
canFire = false;
setTimeout(allowFire, 3000);
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode === 39) {
rightPressed = true;
} else if (e.keyCode === 37) {
leftPressed = true;
}
if (e.keyCode === 32 && canFire == true) {
spacePressed = true;
lasers.push(new newLaser())
}
}
Note that 3000 is the cooldown there.
This will limit the amount of bullets at the same time in the screen, as the player will only shoot every x milliseconds, if you wanna a exact amount of bullets, you can do a var for them with the desired amount, then remove one every time that the player press space, and do a check for > 0 here: (e.keyCode === 32 && canFire == true)
For the meteors if you're going to use the array, to make them fall random you can use this function(found in Mozilla Developers):
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
So you can use it for the coordinates and for the time you can use a timeout(like above) with a random time too, using this(from the same source):
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
If it's a array you can use it like getRandomArbitrary(i * 1000, i * 3000) as i being the index in a for loop. It depends on how specifically you wanna them to work, there's many ways to do that, a function that call itself, while loop, etc.
"It works fine but I want to limit the number of lasers that can be on the screen at once so the player doesn't just spam the space bar to win."
So it sounds like what you want to do is not limit the amount of bullets, but limit the ability of the player to shoot. You could ensure that some time (a tenth of a second?) must pass before the player can shoot again.
As for random numbers, see the later examples here on how to get random numbers in some range.

Javascript move target around screen?

So I'm working on a basic shooter, part of which involves moving a target around the screen. I'm using babylon.js as the engine and my goal is to have the target appear for 0.75 seconds on the screen, then disappear for 0.5 seconds, then reappear at a different random location. The current code I have for that is this:
function moveTarget(canvas, scene){
setTimeout( function (){
scene.meshes[10].visibility = 0; //how I access the target object
randX = genRandNum(minX, maxX); //This is a separate function that works
randY = genRandNum(minY, maxY);
scene.meshes[10].position = new BABYLON.Vector3(randX, randY,
scene.meshes[10].position.z);
scene.meshes[10].visibility = 1;
x ++;
if (x < amount){
moveTarget(canvas, scene);
}
}, tarDuration * 1000)
}
which succeeds in everything except the 0.5 second delay between appearances of the target, ie currently it flashes from location to location with no space in between. I'm thinking that I need a second setTimeout but I'm not entirely sure how to include that or where it would go. Any pushes in the right direction would be much appreciated.
The way I would do this is to set a timeout for the full cycle time (0.75 s + 0.5 s) and then another timeout inside that for the 0.5 s delay.
function moveTarget(canvas, scene){
setTimeout( function (){
setTimeout( function(){
// Your other code
x ++;
if (x < amount){
moveTarget(canvas, scene);
}
}, yourDelayHere)
}, tarDuration * 1000)
}
Where yourDelayHere gives the desired 0.5 s delay. I created a Babylon.js playround which shows a simplified example here.

How to call a function every 1-3 second?

My goal is to write a mini-game using canvas, one of the task is to create "bug" object entering the scene between every 1-3 seconds. I did try functions like setTimeOut,setInterval but I couldn't get it right. Here is my attempt
bugs =[];
function addBug(){
var bug = createBug();
bugs.push(bug);
}
function createRandomNumber(max){
return Math.floor((Math.random() * max) + 1);
};
var enterBug = setInterval(addBug,createRandomNumber(10)*1000);
currently I got it spawning at constant rate but don't know how to change it to every 1-3.Any suggestion? thanks in advance.
Currently, you are only setting the rate once at initial setInterval call. You would likely need to use setTimeout like this:
...
function addBug(){
...
bugTimeout = setTimeout(addBug, createRandomNumber(10)*1000);
}
...
bugTimeout = setTimeout(addBug, createRandomNumber(10)*1000);
You also may think about your random number generation if you want to get more randomness. Right now you can only get exact second values 1-10 since you are multiplying by 1000 to convert to seconds AFTER the random generation is done. If you want something more random you might use:
function createRandomNumber(maxSeconds){
minSeconds = 1;
if (maxSeconds < minSeconds) {
maxSeconds = minSeconds;
}
interval = maxSeconds - minSeconds;
return (Math.floor(Math.random() * interval) + minSeconds) * 1000;
};
You of course would not need to multiply by 1000 anymore when setting timeout.
bugTimeout = setTimeout(addBug, createRandomNumber(10))

delay between function in loop jquery

I have a jQuery function that shows modal boxes:
function ShowAnonce(){
...
jQuery(".ShowAnonce").show();
jQuery(".ShowAnonce").animate({opacity: 1},300).delay(1800).animate({opacity: 0},300);
}
And what I want to do is to show this box 10 times with different random intervals. I used a for loop and setTimeout like this:
for(i=0;i<10;i++){
setTimeout(ShowAnonce(),Math.random()*100);
}
but it shows the box 10 times with no delay. What can I do to fix it?
Also, why can't I do the following at the end of ShowAnonce function?
jQuery(".ShowAnonce").hide();
If I do it, it doesn't shows me box because style display:none keeps being assigned.
Math.random() can return value in decimals also like , 0.123. Which the setTimeout() cannot take . Try Math.ceil (Math.random()) this will give you an integer but might give the same value again and again .
I would try (Math.ceil (Math.random()) *10 ).
As an alternative you can use setInterval as below instead of for loop for x number of times:
var x = 0;
var intervalID = setInterval(function () {
ShowAnnounce();
if (++x === 10) {
window.clearInterval(intervalID);
}
}, Math.random()*100);
Another post about each() iteration gave me an answer. So it works for me:
var time = 0;
for(i=0;i<10;i++){
time = time + Math.random() *10000;
setTimeout(ShowAnonce, time);
}

Recursive function to print numbers in JavaScript

I'm trying to make a recursive function to print 1 to 10 in JavaScript, my current code is:
function rec10(x)
{
if (x < 10)
{
$('#text').val(x+1);
x = x+1;
rec10(x);
}
}
The problem is, everytime I activate this function, the text box only shows "10" directly, i want the code to move from 0 to 1, to 2... until 10. Showing each one of them in the text box.
I tried to use setInterval and setTimeout but I didn't figure it out how to work with that. Thank you very much
instead of:
rec10(x);
call
setTimeout(function() { rec10(x); }, 1000);
With setInterval you can using code below:
function rec10(x) {
var interval = setInterval(function() {
if (x >= 10) clearInterval(interval);
$('#text').val(x++);
}, 1000);
}
JavaScript is single threaded, which means while your code runs, the changes you make to the DOM won't be seen on the browser until your code finish.
You need to give control to the browser for couple of seconds, it can be done with setTimeout:
function rec10(x){
if (x < 10){
$('#text').val(++x);
setTimeout(function(){
rec10(x);
},20);
}
}
Did you resort to setInterval/setTimeout only because you can't make a working recursive function?
If that's the case, how about this recursive function below without using setInterval/setTimeout:
function rec10(x) {
if (x <= 10) {
if (x <= 0) x = 1;
//append?
$('#text').val(x);
rec10(x + 1);
}
}
rec10(1);
But the problem with the code above is it will happen so fast you won't notice the printing of numbers 1 up to 9.
If you want to see the those numbers then I suggest you just append the value to your placeholder $('#text').
But if you really wanna see the numbers being printed and then being replaced by the next number, then you can refer to the answers posted by other users which uses setInterval/setTimeout.

Categories

Resources