I'm trying to create a very simple 2D game where you run forward automatically and then jump at keypress to avoid obstacles along the course.
I made this so far. The only issue is that jumping "stops" the forward-motion. And if you for example hold the up button it stops the entire game and you keep flying upwards like a bird...
Can anyone give me some advice on how to fix it? I would also LOVE it if someone could guide me in how to place 1-2 random obstacles along the course and restart the game, also show total position left traveled if those obstacles are hit by the user.
My plan is to speed up the game every time you finish a course!
Thanks a lot in advance :)
<div style='' id='map'></div>
$(function(){
var unjump = function(){
$('#player').stop().animate({
bottom: '33'
});
}
var jump = function(){
$('#player').stop().animate({
bottom: '+=100'
});
setTimeout(unjump, 1000);
}
$(document).keydown(function(e) {
switch(e.which) {
case 38: // up
jump();
break;
}
});
var player = '<div id="player"></div>';
$("#map").append(player);
function run(){
var position = $('#player').position();
var width = $('#map').width();
if (position.left > width){
$("#player").css( "left", 0 );
}
$('#player').stop().animate({
left: '+=200'
});
}
run = setInterval(run, 100);
});
DEMO
the main error was in css positioning of player
css code
#player{
width:10px;
height:10px;
border:solid;
position:absolute;
bottom:0px;
}
#map{
position:relative;
}
html code
<div style='border:solid ;height:100px' id='map'></div>
js code
var interval = null;
var interval2 = null;
$(function () {
var player = '<div id="player"></div>';
$("#map").append(player);
var unjump = function () {
$('#player').stop().animate({
bottom: '0'
});
};
var jump = function () {
$('#player').stop().animate({
bottom: '+=100'
}, 500);
interval2 = setTimeout(unjump, 500);
};
$(document).keydown(function (e) {
switch (e.which) {
case 38: // up
jump();
break;
}
});
function run() {
var width = $('#map').width();
if ($('#player').position().left > width) {
$("#player").css("left", 0);
}
$('#player').stop().animate({
left: '+=10'
});
}
interval = setInterval(run, 500);
});
Try this:
https://fiddle.jshell.net/u8deLxkz/2/
Main issue was to perform run animation only if no other animation is running.
Except for that, I tidied up the code a little.
$(function(){
//No need for two separate functions, left is handled here as well
function jump(){
$('#player').animate({
bottom: '+=30',
left: '+=10'
},100).animate({
bottom: '-=30',
left: '+=10'
},100);
}
//I think keyup gives better results
$(document).keyup(function(e) {
switch(e.which) {
case 38: //up
jump();
break;
}
});
var player = '<div id="player" style="width: 50px; height: 50px; background-color: blue; position:absolute; bottom:500px;"></div>';
$("#map").append(player);
function run(){
var position = $('#player').position();
var width = $('#map').width();
$('#player').position()
console.log('pos ' + position.left + "\nwidth: " + width);
if (position.left > width){
$("#player").finish();
$("#player").css( "left", 0 );
}
//Continue with horizontal animation only if jumping is not in progress
if(!$('#player').is(':animated') ){
$('#player').animate({
left: '+=10'
},100);
}
}
var go = setInterval(run, 100);
});
Related
I am new to using javascript and jquery so I'm having some problems figuring this one out.
I am trying to use the animate function in jquery to move a box from one corner to the next.
The box begins on the top-left corner of the screen and upon clicking the 'go' button, it will move to the next corner (top-right).
Clicking the same 'go' button then moves the box to the next corner (bottom-right).
Clicking the 'go' button once more will move it to the next corner (bottom-left).
Clicking the 'go' button once more will move it to the next corner (top-left, which is the start).
I've included a picture to show exactly what I mean by this:
What the program should do!
So, this is what I've got so far:
$(document).ready(function () {
$('#go').click(function(){
var dest = parseInt($('#block').css('margin-left').replace('px', '')) + 100;
if (dest > 0) {
$('#block').animate({
marginLeft: '1800px'
}, 0 );
}
else {
$('#block').animate({
marginLeft: dest + 'px'
}, 0 );
}
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>
I've got the box to move to the top-right corner but cannot figure out how to make it now move down using the same button.
I've tried something with a toggle but it did not work. That looked something like this:
$(document).ready(function () {
$('#go').click(function(){
var toggle = 1
if (toggle == 1){
$("#block").animate({left: "80px"});
toggle = 0;
} else{
$("#block").animate({right: "80px"});
toggle = 1;
}
});
I was thinking of maybe using cases to switch between which coordinates the button will move the box to. However, I have no knowledge of how this works with jquery and the animate function.
If anyone has any other ideas or knows how to use the case switches in this scenario, I would really appreciate it and thank you in advance!
P.S. I've tried searching this answer on here for a couple of hours now and have not found much that will help me. I am hoping this question will serve to help others who are having a similar problem to mine!
Please try this example:
$(document).ready(function () {
var leftValue = window.innerWidth - 115; // 115 is a temp value
var topValue = window.innerHeight - 115;
var actionNum = 0;
var movingBlock = $('#block');
$('#go').click(function () {
if (actionNum < 4) {
actionNum++;
} else {
actionNum = 1;
}
switch (actionNum) {
case 1:
// move to the top right
movingBlock.animate({
left: leftValue + 'px',
top: 0
}, 1000);
break;
case 2:
// move to the bottom right
movingBlock.animate({
left: leftValue + 'px',
top: topValue + 'px'
}, 1000);
break;
case 3:
// move to the left bottom
movingBlock.animate({
top: topValue + 'px',
left: 0
}, 1000);
break;
case 4:
// move to the top left
movingBlock.animate({
left: 0,
top: 0
}, 1000);
break;
default:
break;
}
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
position: relative;
z-index: 1;
}
#go {
z-index: 2;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>
There is a multi solution for your problem ,
So I suggest some simple solution , is that you pput position absolute to your div ,
then change (annimate) the left or top of this last after checking conditions ,
you can get top left position in Jquery using .position() funcion ,
See belwon Snippet (added , 1000 milisseconde in order to show annimation transition )
var widh_annimation = "400px";
var hieght_annimation = "100px";
$(document).ready(function () {
$('#go').click(function(){
var position = $("#block").position();
var annimation = {};
if(position.left == 0 && position.top == 0) {
annimation = { left:widh_annimation};
}else if(position.left > 0 && position.top == 0) {
annimation = { top:hieght_annimation};
}else if(position.left > 0 && position.top > 0) {
annimation = { left:"0"};
}else if(position.left == 0 && position.top > 0) {
annimation = { top:"0"};
}
$('#block').animate(annimation, 1000 );
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
position:absolute;
}
#go {
position:absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>
This question already has an answer here:
jQuery page scroll event logic -- how to throttle
(1 answer)
Closed 6 years ago.
I am trying to mimic the functionality of the following website: www.verbaasd.net. Each scrolling "session" will only trigger one action.
Each time a user scrolls down an action will happen depending on the status of variabel count. I only want this to happen ONCE per scroll. For example if a user has a Macbook with touchpad it will fire multiple times very vast. The count will go from 1 to 4 pretty much instantly. Is there a way to set a timeout or something so it stops for 0.5 sec when variabel count increases or decreases by 1?
Current code:
var count = 1;
$(window).on('mousewheel DOMMouseScroll', function(e) {
if (e.originalEvent.wheelDelta / 120 > 0) {
count -= 1;
} else {
count += 1;
}
if (count < 1) count = 1;
if (count > 4) count = 4;
switch (count) {
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
case 4:
// do something
break;
}
$(".cd-background-wrapper").attr("data-slide", count);
});
I recommend other way.
You should use 'preventDefault' and delay effect using setTimeout.
I wrote a simple prototype code below link.
(only tested on Chrome and safari)
http://codepen.io/nigayo/pen/PNEvmY
[HTML]
<body>
<div id="wrap">
<section>section A</section>
<section>section B</section>
<section>section C</section>
<section>section D</section>
</div>
</body>
[CSS]
body {
overflow: hidden;
height: 100%;
}
#wrap {
position: relative;
width: 100%;
height: 100%;
top: 0;
}
section {
width: 100%;
height: 600px;
}
section:nth-child(1) {
background: red;
}
section:nth-child(2) {
background: blue;
}
section:nth-child(3) {
background: green;
}
section:nth-child(4) {
background: magenta;
}
[JavaScript]
(function() {
var currentPanel = 1;
var wrap = $('#wrap');
var panelsize = 600;
var step = 10;
var interval = 1000;
var direction = 1;
var bAnimation = false;
function animation() {
setTimeout(function() {
var currentTop = parseInt(wrap.css("top"));
if (direction < 0) {
if (currentTop <= minValue) {
setTimeout(function() {
bAnimation = false;
}, interval);
return;
}
} else {
if (currentTop >= minValue) {
setTimeout(function() {
bAnimation = false;
}, interval);
return;
}
}
wrap.css({
"top": currentTop - step
});
animation();
}, 16);
}
$(window).bind('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if (bAnimation) return;
var currentTop = parseInt(wrap.css("top"));
if (event.originalEvent.wheelDelta < 0) {
//down scroll
minValue = currentTop - panelsize;
step = 10;
direction = -1;
} else {
//up scroll
minValue = currentTop + panelsize;
step = -10;
direction = 1;
}
console.log(minValue, bAnimation);
bAnimation = true;
animation();
});
})();
If you refer to my codes, you should use 'jquery animate function' or 'requestAnimationframe' for animation logic.
Answer thanks to A. Wolff. Using _.throttle with lodash.js did the trick! You can find more info here: https://css-tricks.com/the-difference-between-throttling-and-debouncing/
So, I'm trying to make an animation in JavaScript (I want a navigation bar to pull down when I click it). The problem is that every time I click this navigation bar, it only moves down one pixel. How do I make it to where I can make the "Move" function repeat over and over so that it realizes the navigation bar is below "0", and move it up? Here's the code I have atm:
var i = -43 //original position of div
function Move(x)
{
if (i < 0)
{
i++;
x.style.top = i + "px";
}
}
function setPosition(x)
{
setInterval(Move(x), 500);
}
P.S. I have the "div onclick" equal to "setInterval(this)"
I would use a setTimeout() (so you don't have to worry about canceling the setInterval()), and note the use of an anonymous function (function(){}) for the first argument of the setTimeout() call:
#slider {
position: absolute;
top: -43px;
left: 200px;
width: 200px;
height: 50px;
border: 1px solid blue;
background: #dff;
}
<div id='slider'>This is a slidout</div>
<div id="clicker">Click me!</div>
var slider = document.getElementById('slider'),
clicker = document.getElementById('clicker');
clicker.onclick = function(){
Move(slider, -43);
};
function Move(x, i)
{
if (i < 0)
{
i++;
x.style.top = i + "px";
setTimeout(function(){
Move(x, i);
}, 50);
}
}
http://jsfiddle.net/h2C3A/
I have a JQuery function that makes a nav bar slide up or down as you scroll vertically. The idea is to always keep the navbar 20 pixels from the top of the client window. When the user scrolls up or down, the nav bar slides till it is back to 20 pixels from the top of the client window.
My Problem: It just wont bloody move lol. What have I done wrong?
Here is my JSFiddle with JQuery code: http://jsfiddle.net/wLga8/
Here is my code:
function moveDistanceEaseIn( /*HTML Element*/ ele, /*int|float*/ dist, /*Function*/ funct )
{
ele = $(ele);
var min = dist*0.01;
// kill an already running animation
if (ele.data("animInterval"))
clearInterval(ele.data("animInterval"));
var step = function()
{
if (dist <= min)
{
ele.data("animInterval", false);
clearInterval(interval);
return;
}
var stepMove = dist*0.1;
dist -= stepMove;
funct(ele, dist, stepMove);
};
var interval = setInterval(step, 30);
ele.data("animInterval", interval);
}
function moveToPointEaseIn( /*HTML Element*/ ele, /*int|float*/ curPoint, /*int|float*/ point, /*Function*/ funct, /*bool*/ signed )
{
ele = $(ele);
var dist = (signed == true) ? curPoint - point:Math.abs(curPoint - point);
moveDistanceEaseIn(ele, dist, funct);
}
$(document).ready(function()
{
$(window).scroll(function ()
{
var nav = $("#aa");
moveToPointEaseIn(nav, nav.position().top, $(window).scrollTop()+20, function(ele, dist, stepMove)
{
ele.css("top", ele.position().top+stepMove);
}, true);
});
});
And some example HTML:
<body style="height: 3000px;">
<div id="aa" style="position: absolute; left: 0px; top: 20px; width: 200px; height: 500px; background-color: red;"></div>
</body>
I'm not certain why your function isn't working. The fiddle wasn't set to use jquery, but even setting that has no effect.
However, this seems to do what you're after....
<body style="height: 3000px;">
<div id="aa" style="position: absolute; left: 0px; top: 20px; width: 200px; height: 500px; background-color: red;">
</div>
var $scrollingDiv = $("#aa");
$(window).scroll(function(){
$scrollingDiv.stop().animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, 20 );
});
DEMO
Not sure if it will solve all of your problem, but these should at least get you up and running so you can debug your code further:
Add the jQuery library to your fiddle (missing in the one you posted)
The first time your step function runs, the values are negative: -100 and -1. This means your <= test will kill your animation on the first iteration
I hacked around this by changing this line:
if (dist <= min)
To this:
if (Math.abs(dist) <= Math.abs(min))
The animation still looks wrong, but at least it is animating :)
Here's the modified fiddle: http://jsfiddle.net/wLga8/4/
This is a function thats supposed to move an image slowly to the right, it isnt working... what did i mess up?
<script type="text/javascript">
var userWidth = window.screen.width;
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left);
var tim = setTimeout("moveRight(id, speed)",50);
right = right+speed; // move
if (right > window.screen.height / 2)
{
right=0;
pp.style.left = right+"px";
}
}
</script>
Looks like id and speed aren't getting passed into moveRight(). When they're in the string as you have them they won't get evaluated. Have a look at this, it seems to do the trick. I stripped it down a little.
<div id="test" style="width: 50px; height: 50px; left: 0px; background-color: #000; position: absolute;"> </div>
<script type="text/javascript">
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left) || 0;
right += speed; // move
pp.style.left = right + "px";
var move = setTimeout(function() {
moveRight(id, speed);
}, 50);
}
moveRight('test', 1);
</script>
A jsfiddle to play with. You can tweak it to your liking.