I am making a platform game in JavaScript and I need some help.
How do I make an image jump up 50px in JavaScript when the spacebar pushed then fall back to a certain position?
If you mean jumping as in jumping with gravity - you'd need a parabola formula.
E.g.: http://jsfiddle.net/pimvdb/7JFU3/.
var x = 0;
var interval = setInterval(function() {
x++;
image.style.top = 50 - (-0.1 * x * (x - 50)) + 'px';
if(x >= 50) clearInterval(interval);
}, 20);
I'm working on exact the same thing. Here's my github project link https://github.com/beothorn/webcomicsgame
Look at MainCharacter.js at
if(gameCommandState.up){
if(this.canJump(game))
this.element.yAccelerate(-this.yAcceleration);
}
You can fork it if you want, but I'm doing it using canvas.
We had fun extending this to have an image keep bouncing up and down
var x = 0;
var goingUp = true;
var interval = setInterval(function() {
if(goingUp==true) {
x++;
if(x >= 50) {
goingUp=false;
//alert("go down")
}
} else {
x--;
if(x <= -50) {
goingUp=true;
//alert("go up")
}
}
$('#demo').css('top', 50 - (-0.1 * x * (x - 50)));
}, 20);
Related
Everything was going smoothly until now. I want to have this hor() function reverse after 20 seconds. The original hor() function grabs an image offscreen and moves it horizontally from the left to the center of the page. I'd like to create a function that does the opposite after 20 seconds. The "after 20 seconds" part is giving me the most grief. If you could show me what a new function would look like or an 'else' addition to the current function that would be great. Thanks.
<script language="JavaScript" type="text/JavaScript">
var x = -500;
var y = 100;
function hor(val) {
if (x <= 500){
x = x + val;
document.getElementById("pos").style.left = x + "px";
setTimeout("hor(5)", 10);
}
}
</script>
<style type="text/css">
<!--
#pos {
position: absolute;
left: -500px;
top: 100px;
z-index: 0;
}
</style>
<body onLoad="setTimeout('hor(5)',5000)">
<div id="pos">
<img src="image.jpg">
</div>
Perhaps you could try changing the script to this:
// Define variables
var x = -500,
y = 100,
direction = 1;
// Function which moves "pos" element
function hor(val) {
// Move by specified value multiplied by direction
x += val * direction;
if(x > 500){
x = 500;
// Reverse direction
direction = -1;
} else if(x < -500){
x = -500;
// Reverse direction, once again
direction = 1;
}
// Move element
document.getElementById("pos").style.left = x + "px";
// Continue loop
setTimeout("hor("+val+")", 10);
}
This code will continue moving the pos element by the specified value until x greater than 500, at which point it will switch direction, then continue until x reaches -500, and so on.
EDIT:
This code will fix that issue with 20 seconds (I had thought that the 500 pixel thing computed to 20 seconds, lol).
// Define variables
var x = -500,
y = 100,
direction = 1;
firstCall = true;
timeElapsed = 0;
// Function which moves "pos" element
function hor(val) {
// Don't let the first call count!
if(!firstCall)timeElapsed += 10;
else firstCall = false;
if(timeElapsed >= 2000){
// Reverse direction
direction *= -1;
timeElapsed = 0;
}
// Move by specified value multiplied by direction
x += val * direction;
// Move element
document.getElementById("pos").style.left = x + "px";
// Continue loop
setTimeout("hor("+val+")", 10);
}
Try this. Here the img is moved horizontally and after sometime it is reverted back to its original position.
<script>
var x = -500;
var y = 100;
var op;
function hor(val) {
if (x <= 500 && x>=-500) {
x = x + val;
document.getElementById("pos").style.left = x + "px";
setTimeout(function(){hor(val);},10);
}
}
$(document).ready(function(){
setTimeout(function(){hor(5);},1000);
setInterval(function(){
setTimeout(function(){hor(-5);},1000);
},2000);
});
</script>
I have changed the timings for testing purpose only, you can change it back.
var move = function() {
Xpos = Math.round(Math.random() * 95);
food[num].css('left', Xpos + '%');
interval = setInterval(function() {
console.log(i);
var posTop = food[num].offset().top / $(window).height() * 100;
while(posTop < 80) {
if(posTop === 80) {
num++;
break;
}
posTop += 1;
food[num].css('top', posTop + '%');
break;
}
}, speed);
}
//Color the circle
circleColor();
move();
}
OK so this is my code. It creates a circle(a <div> element) on top of the screen and gives it a random x coordinate. Than it puts it in food[] array. The entire code starts by clicking the button, but every time I press the button again the circle that was last moving stops, function creates a new one and the new one moves. Is there a way I can make all elements in the array move without depending on each other?
http://jsfiddle.net/yqwjqx31/
I understand why this happens but I have no idea how to fix it.
First you're using a global variable num in setInterval function handler, so its value get modified while using it in new cercle create, secondly you're clearing interval of the last cercle you created before creating a new cercle. It means you're sharing the same interval between all cercles. Use instead an array of intervals just like var food =[] and use a temporary variable to prevent the index value modification inside your setInterval handler. Here's a working fiddle
//Interval
var interval =[];
var tempNum = num;
interval[num] = setInterval(function() {
var posTop = food[tempNum].offset().top / $(window).height() * 100;
while(posTop < 80) {
if(posTop === 80) {
break;
}
posTop += 1;
food[tempNum].css('top', posTop + '%');
break;
}
}, speed);
Increment your num variable
//Color the circle
circleColor();
move();
num++;
Your move function is only responsible for moving the last generated div via createCircle. If you want to move them all till collision, you need to loop through them all and move them accordingly. Or, you can animate them via CSS.
Here is the working version :
http://jsfiddle.net/yqwjqx31/3/
Notice how the setInterval callback loops through all the div and pushes them down until their height is 80.
var move = function () {
interval = setInterval(function () {
for (var i = 0; i < food.length; ++i) {
var posTop = food[i].offset().top / $(window).height() * 100;
if (posTop < 80) posTop += 1;
food[i].css('top', posTop + '%');
}
}, speed);
}
I have to repair bottom slider on http://rhemapress.pl/www_wopr/ . If you see when you click right arrow twice, then animation back to start and animate again. Here when i click one on right arrow time this should be blocked and not possible to click second time.
Numer of moves right is created dynamicly by checkWidth();
function checkWidth() {
var elements = $('.items').children().length;
var width = Math.ceil(elements / 5) * 820;
return width;
}
This return realWidth witch is something like limit of offset. Variable offset is setted to 0 at start. So, if i click right, then in method moveRight() is checked if element can be moved and it's move. At end offset is increment by 820px (one page of slider), so if we've got 2 pages, then next move can't be called. But it is and this is problem! :/
My code
<script type="text/javascript">
$(document).ready(function() {
$('a.prev').bind('click',moveLeft);
$('a.next').bind('click',moveRight);
var realWidth = checkWidth();
realWidth -= 820;
var offset = 0;
function moveLeft(e) {
var position = $('.items').position();
var elements = $('.items').children().length;
if ((elements > 5) && ((offset - 820) >= 0) ) {
$('.items').animate({
'left': (position.left + 820)
}, 300, function() {
offset -= 820;
});
}
}
function moveRight(e) {
var position = $('.items').position();
var elements = $('.items').children().length;
if ((elements > 5) && ((offset + 820) <= realWidth)) {
$('.items').animate({
'left': (position.left - 820)
}, 300, function() {
offset += 820;
});
}
}
function checkWidth() {
var elements = $('.items').children().length;
var width = Math.ceil(elements / 5) * 820;
return width;
}
});
</script>
How can i do this correctly?
It seems like you want to prevent the click event from firing before the current animation is complete. You can do this by preventing the rest of the function from executing if the element is currently being animated:
function moveLeft(e) {
if ($(this).is(":animated")) {
return false;
}
Is there any way to emulate a scroll type option using jquery animate? Right now it simply scrolls equivalent to the value you give it (like below). I cannot do a custom scroll bar on this div because its mainly geared towards making it easy to scroll on mobile devices. So the example below will scroll buy it goes -100px from the top, but then stops, and repeats. Is there any easy way to make this a transition that it will just continue.
jQuery(".down-arrow").mousedown(function(){
var height = jQuery("#technology_list").height();
//if($('#technology_list').offset().top
scrolling = true;
startScrolling(jQuery("#technology_list"), "-=100px");
//jQuery("#technology_list").animate({top: '-=25'});
}).mouseup(function(){
scrolling = false;
});
function startScrolling(obj, param)
{
obj.animate({"top": param}, "fast", function(){
if (scrolling)
{
startScrolling(obj, param);
}
});
jsFiddle showing it in action
Simplest answer would be that you want to make sure you set your animate to have easing set to linear.
.animate( { /* whats animating */ } , duration: 'XXX', easing: 'linear'
,function () { /* callback */ }
);
Strangely enough, when easing is left out of animate() its default actually isn't linear (which basically turns it off). The default is a standard easing, which eliminates that "smoothness", one speed through out the entire animation that we'd want here.
Here's an example so you can see it:
var end = 20;
for (i = 0; i < end; i++) {
$('#test').animate({'top': '+=50px'}, 500, 'linear', function () {
// callback
});
}
I had the same problem a little while ago and put this together, basically it is an infinite scroll solution:
EDIT: Here is my code adapted for your use case:
// Assuming you also have/want a scroll up
jQuery(".up-arrow").mousedown(function() {
// You don't need to use jQuery instead of $ inside of jQuery defined functions
var offset = $("#technology_list").offset();
var topValue = offset.top;
if ((topValue * 2) < 1000) speed = topValue * 3;
else if ((topValue * 2) < 500) speed = topValue * 4;
else if ((topValue * 2) < 100) speed = topValue * 8;
else speed = topValue * 2;
$("#technology_list").animate({
top: 0
}, speed);
}).mouseup(function() {
$("#technology_list").stop();
});
jQuery(".down-arrow").mousedown(function() {
var offset = $("#technology_list").offset();
var topValue = offset.top;
var height = $("#technology_list").height();
if (((height - topValue) * 2) < 1000) speed = (height - topValue) * 2;
else if (((height - topValue) * 2) < 500) speed = (height - topValue) * 2;
else if (((height - topValue) * 2) < 100) speed = (height - topValue) * 2;
else speed = (height - topValue) * 2;
$("#technology_list").animate(function() {
top: $("#technology_list").height()
}, speed);
}).mouseup(function() {
$("#technology_list").stop();
});
End of edit.
$(".scroll-left").hover(function() {
if (($(this).parent().scrollLeft() * 2) < 1000) speed = $(this).parent().scrollLeft() * 3;
// If it is less than 500 pixels from the edge, then it takes 3 times as long as the scrollLeft value in milliseconds. (Sorry about the if's being hard to read)
else if (($(this).parent().scrollLeft() * 2) < 500) speed = $(this).parent().scrollLeft() * 4;
// And if it is less than 250 pixels, it takes 4 times as long
else if (($(this).parent().scrollLeft() * 2) < 100) speed = $(this).parent().scrollLeft() * 8;
// Less than 50, it takes 8 times as long
else speed = $(this).parent().scrollLeft() * 2;
// And if it is more than 500 run it at 2 milliseconds per pixel
$(this).parent().animate({
scrollLeft: 0
}, speed);
// Scroll it to the beginning at the above set speed
}, function() {
$(this).parent().stop();
// On mouseOut stop the animation
});
$(".scroll-right").hover(function() {
parent = $(this).parent()[0];
parentWidth = $(this).parent()[0].scrollWidth;
// Cache parent and parentWidth (stops delay on hover)
if (((parentWidth - parent.scrollLeft) * 2) < 1000) speed = (parentWidth - parent.scrollLeft) * 2;
// Pretty much the same thing as before but this time it sort of makes a "scrollRight"
else if (((parentWidth - parent.scrollLeft) * 2) < 500) speed = (parentWidth - parent.scrollLeft) * 2;
else if (((parentWidth - parent.scrollLeft) * 2) < 100) speed = (parentWidth - parent.scrollLeft) * 2;
else speed = (parentWidth - parent.scrollLeft) * 2;
$(this).parent().animate({
scrollLeft: $(this).siblings(".row-scroll").width()
}, speed);
// Same thing as before, but this time we scroll all the way to the right side
}, function() {
$(this).parent().stop();
});
This is directly copied from my code but the idea is sound, the multiplication slows it down when it is close to the edge.
It isn't perfect or near it and if you want something more fine-tuned then you should try Pause
You could try using the jQuery plugin ScrollTo: http://demos.flesler.com/jquery/scrollTo/
I've been trying to get this javascript animation to work for hours now, and I got nothing. The problem isn't getting my div box to move from left to right(or from top to bottom), it's the opposite of each case that I have trouble with it. Here's what I have so far(In addition, I have set boundaries set to keep my moving box contained within the view window so if it hits any one of sides, it should move to the opposite direction). Any help is awesome at this point.
Note: the next step is to create a bouncing effect for the box, but i'll worry about that once i get simple animation working.
setInterval(function(){
if(parseInt(box.style.left) > parseInt(viewDim.width - 57)){
box.style.left -= parseInt(box.style.left) - 2 + 'px';
/* } else if(parseInt(box.style.left) < 0){
//debug_log("HIT!!");
//parseInt(box.style.left) += 2 + 'px';
} else if(parseInt(box.style.top) > parseInt(viewDim.height-58)){
} else if(parseInt(box.style.top) < 0){*/
} else {
box.style.left = parseInt(box.style.left) + 2 + 'px';
//box.style.top = parseInt(box.style.top) + 5 + 'px';
}
}, 20);
Code like this always works for me:
var boxWidth = 57, delta = 2;
setInterval(function(){
var left = parseInt(box.style.left);
if(left >= parseInt(viewDim.width - boxWidth)){
delta = -2;
}
if (left <= 0) {
delta = 2;
}
box.style.left = left + delta + 'px';
}, 20);
Although you have your solution now, I couldn't help myself from making complete code here.
The bouncing box bounces around inside the parent element. Tested in IE8, FF3, and Opera11.
This can give an idea, how to do it with jQuery
http://jsfiddle.net/rFkpy/
$('#myDiv').click(function() {
$(this).animate({
left: '+=250'
}, 1500, "easeOutBounce", function() {
// callBack
});
});