make an image move inside a div randomly - javascript

I'm creating a simple game and i am stuck currently at something i have a div called 'box' and an image inside it called 'Parachute' when the game start the parachute should move randomly inside the border of the div
my code :
<div id="box">
</div>
<script type="text/javascript">
var ToAppend = "<img src='Parachute.gif' width='25px' height='25px' class='Parachute' /> ";
setInterval(function () {
for (var i = 1; i <= 2; i++) {
$("#box").append(ToAppend);
MoveParticles();
}
}, 3000);
function MoveParticles() {
$(".Parachute").each(function () {
var x = Math.floor(Math.random() * 400);
var y = Math.floor(Math.random() * 400);
$(this).animate({ "left": x + "px" }, "slow");
$(this).animate({ "top": y + "px" }, "slow");
});
}
<script>

You seem to be animating #box, not .Parachute.
Here's a demo to get you in the right track.
//let's build the chutes
for (var i = 0; i < 50; ++i) {
$('<div/>', {
class: 'chute'
}).appendTo('#box');
}
//cache a few static values
var box = $('#box');
var width = box.width();
var height = box.height();
var chute = $('.chute');
//our main animation "loop"
chute.each(function foo() {
//generate random values
var top = (Math.random() * height) | 0;
var left = (Math.random() * width) | 0;
var time = Math.random() * (800 - 400) + 400 | 0;
//animate
//we introduce a random value so that they aren't moving together
//after the animation, we call foo for the current element
//to animate the current element again
$(this).animate({
left: left,
top: top
}, time, foo);
});

Related

How can I make images going down the screen randomly and at a certain speed (video game js)?

I am building a game where a spaceship moves into the screen with PC controllers. Now, my remaining part is to make a fireball images drop of the screen randomly with a precise speed and quantity (because the image is only one, we have to multiplicate it). Can someone achieve this?
Here is the code:
Fireball image:
<img src="Photo/fireball.png" id="fireball">
Spaceship image:
<img src="Photo/Spaceship1.png" id="icon-p">
Spaceship moving with controllers + prevent it from going out of screen:
let display = document.getElementById("body");
let rect = icon;
let pos = { top: 1000, left: 570 };
const keys = {};
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true
});
window.addEventListener("keyup", function(e) {
keys[e.keyCode] = false
});
const loop = function() {
if (keys[37] || keys[81]) { pos.left -= 10; }
if (keys[39] || keys[68]) { pos.left += 10; }
if (keys[38] || keys[90]) { pos.top -= 10; }
if (keys[40] || keys[83]) { pos.top += 10; }
var owidth = display.offsetWidth;
var oheight = display.offsetHeight;
var iwidth = rect.offsetWidth;
var iheight = rect.offsetHeight;
if (pos.left < 0) { pos.left = -10; }
if (pos.top < 0) { pos.top = -10; }
if (pos.left + iwidth >= owidth) { pos.left = owidth - iwidth; }
if (pos.top + iheight >= oheight) { pos.top = oheight - iheight; }
rect.setAttribute("data", owidth + ":" + oheight);
rect.style.left = pos.left + "px";
rect.style.top = pos.top + "px";
};
let sens = setInterval(loop, 1000 / 60);
// Random X coordiante
function rndScreenX(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset));
}
// Set fireball coordinates (X is random)
let fireballElement = document.querySelector('#fireball');
let fireball = {
x: rndScreenX(fireballElement.offsetWidth),
y: 0
}
const loop = function() {
// Change fireball Y
fireball.y += 10;
fireballElement.style.top = fireball.y + 'px';
if (fireball.y > window.innerHeight) {
// Fireball is out of window
// Reset Y and get new random X
fireball.x = rndScreenX(fireballElement.offsetWidth);
fireballElement.style.left = fireball.x + 'px';
fireball.y = 0;
}
};
fireballElement.style.left = fireball.x + 'px';
let sens = setInterval(loop, 1000 / 60);
#fireball {
position: absolute;
/* Ignore this rule if you're using an image */
width: 50px;
height: 50px;
background: red;
border-radius: 40% 40% 50% 50%;
}
<img src="Photo/fireball.png" id="fireball">
This solution includes three configurable variables: spawnRate, advanceRate, and fallDistance. It uses them to determine how often new fireballs spawn, how often they move down the screen, and how far they move on each 'tick'.
The "main" part of the script consists of two setInterval calls, one to handle spawning new fireballs, and the other to handle advancing them down the screen.
(See the in-code comments for further explanation.)
const
display = document.getElementById("display"), // Container element
fireballs = [], // Array to hold all fireball objects
fallDistance = 6; // Measured in `vh` units (but could be whatever)
spawnRate = 2000,
advanceRate = 500;
// Adds the first fireball immediately
spawnFireball(fireballs);
// Moves all fireballs down every 500 milliseconds
const advancerTimer = setInterval(
function(){ advanceAll(fireballs, fallDistance, display); },
advanceRate
);
// Spawns a new fireball every 2000 milliseconds
const spawnerTimer = setInterval(
function(){ spawnFireball(fireballs); },
spawnRate
);
// Defines a function to add a fireball to the array
function spawnFireball(fireballs){
const
img = document.createElement("img"), // Element to add to screen
x = Math.floor(Math.random() * 96) + 2, // Random `x` position
y = 3; // `y` position starts near top of screen
img.src = "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.UyMqod0eO6Qcmco1Zrmj0QAAAA%26pid%3DApi&f=1",
img.classList.add("fireball"); // To style fireballs
img.style.left = x + "vw"; // `x` position will never change
newFb = { x, y, img }; // `fb` object includes coords + img element
fireballs.push(newFb); // Adds the new fireball to the array
}
// Defines a function to advance a fireball's position
function advance(fb, distance){
fb.y += distance;
}
// Defines a function to draw a fireball in the container
function draw(fb, container){
if(fb.y > 100){ return; } // Ignores below-screen fireballs
fb.img.style.top = fb.y + "vh"; // Updates the location on screen
container.appendChild(fb.img); // The `img` property holds our DOM element
}
// Defines a function to advance and draw all fireballs
function advanceAll(fireballs, distance, container){
for(let fb of fireballs){
advance(fb, distance);
draw(fb, container)
}
}
#display{ height: 99vh; width: 99vw; position: relative; }
.fireball{ height: 2em; width: 2em; position: absolute; }
<div id="display"></div>

Restarting the animation once all divs are clicked?

I am trying to get the script to run again after all the gifs have been clicked and changed to the png's. Once all the gifs are clicked I have to refresh the browser in order for the game to start again. I would preferably like to have the creation of a newDiv happen when one of the divs is clicked. So that way a new one appears when one is clicked, and is constantly adding the newDiv. Any ideas on how to do that would help.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Shoo Fly</title>
<style>
div.a {
width: 200px;
height:200px;
position:absolute;
background-image: url("fly.gif");
}
html {
background: url("fly-background.png");
background-size: cover;
background-repeat: no-repeat;
margin: 0;
padding:0;
background-color: #50BBAD;
zoom: 80%;
}
</style>
<script src="jquery-3.1.1.js"></script>
<script src="please-work.js"></script>
</head>
<body>
<div class="animatedDivs"></div>
</body>
</html>
Javascript:
$(document).ready(function () {
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //5
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //10
});
function newDiv() {
var $div = $("<div class='a'>");
$(".animatedDivs").append($div);
animateDiv();
$div.click(function(){
$div.css('background-image','url(splatter-1.png)');
$div.css('zIndex' , '-1');
$div.css({'position': 'absolute'});
//$(this).data('clicked', true);
var offset = $div.position();
$div.stop();
$div.position({left:(offset.left), right: (offset.right)});
});
function animateDiv() {
var newq = makeNewPosition();
var oldq = $div.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$div.animate({
top: newq[0],
left: newq[1]
}, speed, function () {
animateDiv();
});
};
}
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = .1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
A bonus to skip a couple lines and get a new param.
var init = function(x){
for(i=0;i<x;i++){
newDiv();
};
// Onload initialisation
init(10); // OKAY! div amount as argument??
// So possibly a incrental or random amount?
//
// Thanks SO!
ACCEPTED ANSWER
I named your function, to be able to call it again from somewhere else in the code.
Then I added a loop to check if all images have been clicked...
On each click event.
I also changed your images sources... But it is just for my demo.
Here is the whole code working in this CodePen:
$(document).ready(function () {
// Named the init fonction
var init = function(){
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //5
newDiv();
newDiv();
newDiv();
newDiv();
newDiv(); //10
};
// Onload initialisation
init();
function newDiv() {
var $div = $("<div class='a'>");
$(".animatedDivs").append($div);
animateDiv();
$div.click(function(){
console.log("Image clicked");
$div.css('background-image','url(https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAATsAAAAJDM0N2NjNzkxLWEyOGYtNDE5MS05OGQxLTRkMzFkMDA3ZmZjNw.png)');
$div.css('zIndex' , '-1');
$div.css({'position': 'absolute'});
//$(this).data('clicked', true);
var offset = $div.position();
$div.stop();
$div.position({left:(offset.left), right: (offset.right)});
// ===================================
// Check if all images are clicked.
var allClicked=true;
$(".a").each(function(){
if( $(this).css("z-index")!="-1" ){
allClicked=false;
}
});
console.log( allClicked ); // Is true when all images are clicked.
if(allClicked){
console.log("restarting!");
$(".a").remove();
// Re-init the game
init();
}
// ===================================
});
function animateDiv() {
var newq = makeNewPosition();
var oldq = $div.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$div.animate({
top: newq[0],
left: newq[1]
}, speed, function () {
animateDiv();
});
};
}
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = .1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
});
EDIT
To keep the "splats" there and load some new moving divs, only two lines have to be changed:
In CSS :
div.a {
becomes:
div.a, div.splatted {
And in JS :
$(".a").remove();
becomes:
$(".a").removeClass("a").addClass("splatted");
See this CodePen v2.
Well, if all what you want it is to create a new div when one is clicked, you just need to call to your newDiv function from inside the click function handler:
$div.click(function(){
newDiv();
// more code
});
And if, as the title suggests, you want to restart the animation once all divs are clicked, just check if all are already clicked inside the click function handler:
$div.click(function(){
$(this).data('clicked')
if ( allAreClicked() ) {
// code to restart the game
}
// more code
});
function allAreClicked() {
return $('.animatedDivs > div').lenght = $('.animatedDivs > div[data-cliked="true"]').lenght;
}

Array value in randomly positioned div

Using this - random position of divs in javascript as a starting point I am trying to randomly position divs containing text from an array.
Current code (predominately copied Ken Redler's answer in the linked post):
(function makeDiv(){
var divsize = 200;
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
//set up the array to hold the random div content
var boastsText = [];
var i = 0;
$(".boast ul li").each(function() { boastsText.push($(this).text()) });
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'color': color
});
// make position sensitive to size and document's width
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).html(boastsText[i]).appendTo( 'body' ).fadeIn(100).delay(1000).fadeOut(500, function(){
$(this).remove();
makeDiv();
});
})();
The only thing I have really added is the setting up of the array var boastsText = [] and the each function that populates that array.
The problem I have is I need to iterate over the array so each new div created uses the next item as it's content i.e. div 1 uses array item 0, div 2 uses item 1 etc... until it reaches the end of the array and then starts the process again.
I've modified your script a little bit to use a recursive function in order to iterate over the array and maintain the delay and fadeIn/Out you have:
(function() {
//set up the array to hold the random div content
var boastsText = [];
$(".boast ul li").each(function () {
boastsText.push($(this).text());
});
function makeDiv(i){
var divsize = 200;
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
var $newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'color': color
});
// make position sensitive to size and document's width
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).html(boastsText[i]).appendTo('body').fadeIn(100).fadeOut(500, function() {
$(this).remove();
if (i === boastsText.length) return;
makeDiv(++i);
});
}
//Start the recursion
makeDiv(0);
}());

setInterval- Javascript not working

Trying to loop a function.
It's a simple text animation - The text will
1.Fade in left letter by letter and then
2.Fade out up letter by letter.
3.This will repeat, but the text will appear again at another random location on the
page.
When I set the interval delay to 1000, the text appears 4 times in all with a gap of 1 sec each. The first time, the text appears with fade in left, the second & third the text just flashes as a whole and finally, the fade out happens letter by letter.
So, I set the delay to 4700. The animation works as desired, but it is not looping.
http://jsfiddle.net/y5C4G/3/
The callback function in textillate wasn't working too, so i chose setInterval.
HTML :
<span class="brand">
<h1>
<ul class="texts">
<li>E L Y S I U M</li>
<li></li>
</ul>
</h1>
</span>
JS :
$(window).bind("load", function () {
function ShowBrand() {
var docHeight = $(document).height();
var docWidth = $(document).width();
$newSpan = $(".brand");
spanHeight = $newSpan.height();
spanWidth = $newSpan.width();
maxHeight = docHeight - spanHeight;
maxWidth = docWidth - spanWidth;
$newSpan.show().css({
top: Math.floor(Math.random() * maxHeight),
left: Math.floor(Math.random() * maxWidth)
}).textillate({
in: {effect:'fadeInLeft'},
out: {effect:'fadeOutUp'}
});
}
setInterval(ShowBrand,4700);
});
I'm not so sure about what you want to achieve exactly on your animation, but I guess what you would like to do is something like this:
DEMO:http://jsfiddle.net/YKebf/9/
loadTextillate(jQuery);
$newSpan = $(".brand");
$newSpan.show().textillate({ in : {
effect: 'fadeInLeft'
},
out: {
effect: 'fadeOutUp',
callback: function () {
ShowBrand(); //set as a callback function
}
},
loop: true
});
function ShowBrand() {
var docHeight = $(document).height();
var docWidth = $(document).width();
var spanHeight = $newSpan.height();
var spanWidth = $newSpan.width();
var maxHeight = docHeight - spanHeight;
var maxWidth = docWidth - spanWidth;
var newPosTop = Math.floor(Math.random() * maxHeight);
var newPosLeft = Math.floor(Math.random() * maxWidth);
console.log("New Position",newPosTop,newPosLeft);
$newSpan.css({
top:newPosTop,
left:newPosLeft
});
}
CSS:
.brand{
position:absolute;
}
Hope this helps.
Edit: As mentioned by naota, you can set a callback. By doing this you will not be needing any setInterval and also you might not have to modify any code in plugin file in my case. See the updated demo : http://jsfiddle.net/lotusgodkk/y5C4G/6/
Instead of initializing textillate in each interval, why not just change the top and left value of span and rather add loop:true to the textillate.
JS:
$(window).bind("load", function () {
ShowBrand();
$('.brand').textillate({ in : {
effect: 'fadeInLeft'
},
out: {
effect: 'fadeOutUp',
callback: function () {
ShowBrand()
}
},
loop: true,
});
});
function ShowBrand() {
var docHeight = $(document).height();
var docWidth = $(document).width();
$newSpan = $(".brand");
spanHeight = $newSpan.height();
spanWidth = $newSpan.width();
maxHeight = docHeight - spanHeight;
maxWidth = docWidth - spanWidth;
$newSpan.show().css({
top: Math.floor(Math.random() * maxHeight),
left: Math.floor(Math.random() * maxWidth)
});
}
Also, make sure you have .brand positioned.
CSS:
.brand{position:absolute;}
Demo: http://jsfiddle.net/lotusgodkk/y5C4G/6/

Animate Direction using jquery

I created the snow flake with responsive script. Everything seems ok nothing problem. But i want to enhance for the direction of flakes like left to right and right to left and top to bottom like that. I tried but I am not sure where i did the mistake.
Here is the fiddle
Javascript:
var fallingSpeed = Math.floor(Math.random() * 5 + 1);
var movingDirection = Math.floor(Math.random() * 2);
var currentTop = parseInt(jQuery(this).css('top'));
var currentLeft = parseInt(jQuery(this).css('left'));
jQuery(this).css('top', currentTop + fallingSpeed);
alert(currentLeft);
//
//alert(movingDirection);
if (movingDirection === 0) {
jQuery(this).css('left', currentLeft + fallingSpeed);
} else {
// set the snow move to left
jQuery(this).css('left', currentLeft + -(fallingSpeed));
}
How can i move the flake from left to right and right to left?
Any suggestion would be great.
Thanks.
Try step callback function of jquery animate:
$(function(){
var drop = $('.drop').detach();
function create(){
var clone = drop
.clone()
.appendTo('.container')
.css('left', Math.random()*$(document).width()-20)
.html('*')
.animate(
{'top': $(document).height()-20},
{
duration: Math.random(1000)+8000,
complete:function(){
$(this).fadeOut(200,function(){$(this).remove();});
},
step:function (currentTop){
var fallingSpeed = Math.floor(Math.random() * 5 + 1);
var movingDirection = Math.floor(Math.random() * 2);
var currentTop = parseInt(jQuery(this).css('top'));
var currentLeft = parseInt(jQuery(this).css('left'));
jQuery(this).css('top', currentTop + fallingSpeed);
if (movingDirection === 0) {
jQuery(this).css('left', currentLeft + fallingSpeed);
} else {
// set the snow move to left
jQuery(this).css('left', currentLeft + -(fallingSpeed));
}
}
});
}
DEMO

Categories

Resources