JQuery game - Make player move smooth in % values - javascript

We have this really annoying project were we need to make a game in JQuery. I'm having some problems making my character move the way I want him to. I manage to make the character move but he does not move in %. He adds his own width to the "left:" of him and then animates to that position. This is not good, because when you resize the window they do not "scale with it". Basically, can anyone help me make the player move smoothly in % values! Here is my code! (Variables and comments are in Swedish...)
JSfiddle : https://jsfiddle.net/Leqca77h/1/
index.html:
<!doctype html>
<html>
<head>
<title>JQuery spel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/stil.css">
<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="script/start.js"></script>
<script type="text/javascript" src="script/spelareRörelse.js"></script>
</head>
<body onresize="sättSpelareHöjd()">
<header><h1>Jquery spel</h1></header>
<br>
<div id="bana"></div>
</body>
stil.css:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Ubuntu', sans-serif;
}
#bana {
position: relative;
border: 1px solid black;
margin: auto;
width: 99%;
height: 70vh;
}
#spelare1 {
background-color: green;
width: 2.7%;
height: 0;
display: block;
position: absolute;
}
start.js:
$(document).ready(function(){
//var tid = parseInt(prompt("Hur långt ska du spela? (Ange i sekunder)"));
$("#bana").append("<div id='spelare1'></div>");
$("#bana").append("<div id='spelare2'></div>");
sättSpelareHöjd();
});
var knappTryckt1 = true;
function sättSpelareHöjd() {
var spelareHöjd = $("#spelare1").width();
$("#spelare1").css("height", spelareHöjd);
}
spelareRörelse.js (playerMovment.js):
//Spelare 1 rörelse
$(document).keydown(function(e){
if(knappTryckt1) {
if(e.keyCode == 37) {
$("#spelare1").stop().animate({left: "-=" + $(this).width()},5000);
//Pil vänster
}
else if (e.keyCode == 38) {
$("#spelare1").stop().animate({top: "-=" + $(this).height()},5000);
//Pil upp
}
else if (e.keyCode == 39) {
$("#spelare1").stop().animate({left: "+=" + $(this).width()},5000);
//Pil höger
}
else if (e.keyCode == 40) {
$("#spelare1").stop().animate({top: "+=" + $(this).height()},5000);
//Pil ner
}
knappTryckt1 = false;
}
});
$(document).keyup(function(){
$("#spelare1").stop();
knappTryckt1 = true;
});
If you can help! Thanks! :)
JSfiddle : https://jsfiddle.net/Leqca77h/1/

A solution was found! Changing:
"left: "-=" + $(this).width()"
to:
"left: "-=" + 100 + "%""
worked for me!

Related

If scroll is 100px then turn background into red. (Pure JavaScript)

I am having trouble with scroll using if statements.
How can I fix it and any helpful tips will be much appreciated.
if (window.scrollY == '100px') {
document.body.style.backgroundColor = "red";
}
div {
position: absolute;
top: 200%;
font-size: 5vw;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js"></script>
<div> hi </div>
</body>
</html>
You need to listen on scroll event first.
window.scrollY value is integer.
window.addEventListener("scroll", function() {
if (window.scrollY >= 100) {
document.body.style.backgroundColor = "red";
}
});
div {
position: absolute;
top: 200%;
font-size: 5vw;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js"></script>
<div> hi </div>
</body>
</html>
The condition needs to be >= 100, and you need to listen to the scroll event of the window.
Here is a working snippet:
window.addEventListener("scroll", function() {
if (window.scrollY >= 100) {
document.body.style.backgroundColor = "red";
}
});
.container {
position: absolute;
top: 200%;
font-size: 2rem;
}
<div class="container">hi</div>
You can do it as follows -
window.addEventListener("scroll", function() {
if (window.scrollY >= 100) {
document.body.style.backgroundColor = "red";
}else{
document.body.style.backgroundColor = "white";
}
});
*{
transition-duration: 1s;
}
div {
position: absolute;
top: 200%;
font-size: 5vw;
}
<div> hi </div>
In your code, you had written the condition to be window.scrollY == 100px, so it was not working. But once you modify the condition, the code will work as expected.
Also, the else statement or transition effect are not needed, just added them for nice effect.

jquery draggable, making a div not to go outside of the other div frame

i need a draggable div not to go outside of second div frame, so far i managed to make a "collision" basically returning true or false if draggable div is inside the frame of other div. So the thing now is that i cant get this to work, i was trying to get it to a x = 90(example) when it hits the frame and few more examples , but i just can't get this to work. The draggable div doesn't want to go back to position.
Here is a JSFiddle: https://jsfiddle.net/kojaa/x80wL1mj/2/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Catch a ball</title>
</head>
<body>
<div class="catcherMovableArea" id="catcherMovableArea">
<div id="catcher" class="catcher"></div>
</div>
<script src="script.js"></script>
</body>
</html>
.catcherMovableArea {
position: absolute;
border: 1px solid black;
width: 1900px;
top: 90%;
height: 50px;
}
.catcher {
position: absolute;
width: 250px;
height: 30px;
border-radius: 10px;
background-color: black;
top: 20%;
}
let catcher = $("#catcher");
$(document).mousemove(function(e) {
catcher.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit"
});
let catcherOffset = $(catcher).offset();
let CxPos = catcherOffset.left;
let CyPos = catcherOffset.top;
let catcherYInMovableArea, catcherXInMovableArea = true;
while(!isCatcherYinMovableArea(CyPos)){
catcherYInMovableArea = false;
break;
}
while(!isCatcherXinMovableArea(CxPos)){
catcherXInMovableArea = false;
break;
}
});
function isCatcherYinMovableArea(ypos){
if(ypos < 849.5999755859375 || ypos > 870.5999755859375) {
return false;
} else {
return true;
}
}
function isCatcherXinMovableArea(xpos){
if(xpos < 8 || xpos > 1655 ) {
return false;
} else {
return true;
}
}
By default, the collision option will prevent the element from being placed outside of the window. You want to prevent it from moving outside of a specific element.
To do this, use the within option to select which element should be used for containment.
Example:
let draggable = $("#draggable");
$(document).mousemove(function(e) {
draggable.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit",
within: "#container"
});
});
#container { width: 200px; height: 100px; border-style: solid }
#draggable { width: 50px; height: 50px; background-color: black }
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-rc.1/jquery-ui.js"></script>
<div id="container">
<div id="draggable"></div>
</div>

How to move an drag and drop item to a certain position, when located over canvas?

I am working on a Tablet-environment with draggable objects.
The drag & drop works, it is even possible to drag several objects at once, when implemented.
References are :
Reference 1 & Reference 2
This is how the current version of my code looks like:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<!--
Refernces:
* https://wiki.selfhtml.org/wiki/JavaScript/Tutorials/Drag_and_Drop
* https://mobiforge.com/design-development/touch-friendly-drag-and-drop
-->
<style>
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
main1 {
position: relative;
}
div1 {
position: absolute;
top: 0px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
</style>
<title>Clean up</title>
</head>
<body>
<div id ="container">
</div>
<main1 id="main1">
<div1 class="draggable" id="d1-0""></div1>
</main1>
<script>
var nodeList = document.getElementsByClassName('draggable');
for(var i=0;i<nodeList.length;i++) {
var obj = nodeList[i];
obj.addEventListener('touchmove', function(event) {
var touch = event.targetTouches[0];
// Place element where the finger is
event.target.style.left = touch.pageX + 'px';
event.target.style.top = touch.pageY + 'px';
event.preventDefault();
}, false);
}
</script>
</body>
</html>
The idea is, that the red box (div1) can be moved, dragged and dropped everywhere on the screen. But it needs to be moved to its very initial starting position, when it enters the yellow canvas. (The idea is to "clean up" and "move objects back to where they came from".)
You should use jQuery UI's draggable and touch punch for mobile friendliness
Let me know if this is close to what you're looking for and we can adjust as needed
$(document).ready(function() {
$('#div1').draggable();
$('#container').droppable({
drop: function( event, ui ) {
alert("You dropped the red on the yellow");
}
});
$(document).on("click", "#animateBtn", function() {
//Simple animate w/ just specifying the offsets
//$('#div1').animate({top:"250px", left:"250px"});
//Other animate options
$('#div1').animate({
top:"15px",
left:"15px"
}, {
duration:555, //Animation time in pixels
easing:"easeOutQuart" //See https://api.jqueryui.com/easings/
});
});
});
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
body {
position: relative;
}
#div1 {
position: absolute;
top: 0px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
#animateBtn {
position:fixed;
right:10px;
bottom:10px;
display:inline-block;
padding:3px 5px;
background-color:green;
color:white;
border-radius:6px
}
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<title>Drag and Drop</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
</head>
<body>
<div id="container"></div>
<div class="draggable" id="div1"></div>
<div id="animateBtn">Animate</div>
</body>
</html>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<title>Drag and Drop</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
<style>
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
body {
position: relative;
}
#div1 {
position: absolute;
top: 100px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
</style>
<title>Clean up</title>
</head>
<body>
<div id="container"></div>
<div class="draggable" id="div1"></div>
<!--<div id="animateBtn">Animate</div>-->
<script>
$(document).ready(function() {
$('#div1').draggable();
$('#container').droppable({
drop: function() {
$('#div1').animate({top:"100px", left:"100px"});
}
});
});
</script>
</body>
</html>
I didn't see a mention of jQuery but w3schools has a working example that goes without. Could you some touchup though:
/**
* Make object draggable
* #param {Element} element
*/
const addDraggable = (element)=> {
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
const dragMouseDown = e => {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
[pos3, pos4] = [e.clientX, e.clientY];
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
};
const elementDrag = e => {
console.log(e.clientX, e.clientY);
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
[pos1, pos2] = [pos3 - e.clientX, pos4 - e.clientY];
[pos3, pos4] = [e.clientX, e.clientY];
// set the element's new position:
[element.style.top, element.style.left] =
[(element.offsetTop - pos2) + "px", (element.offsetLeft - pos1) + "px"];
};
const closeDragElement = _ => {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
};
element.onmousedown = dragMouseDown;
}
document.addEventListener("DOMContentLoaded", event=> {
_('#logo-top').addEventListener('click', event=> {
event.stopPropagation();
_('#logo-top').classList.toggle('active');
_('nav').forEach( n=> n.classList.toggle('collapsed') );
_('main').classList.toggle('extended');
});
addDraggable( _('#help-text') );
_( '#help' ).addEventListener( 'click', ()=>{ _('#help-text').classList.toggle('active')} );
_( '#help-text-close' ).addEventListener( 'click', ()=>{_('#help-text').classList.toggle('active')} );
});
Another way would be to use the Drag Operations

I need to execute jquery code only on certain resolution at window scroll

I've this jquery code. I need to execute only on > 950px resolution.
If not I lose the responsive logo.
I want to do something similar like the Lenovo homepage navbar.
$(document).ready(function(){
//left side menu functions End
//Logo function
$(document).scroll(function() {
if ($(document).scrollTop() < 25) {
$("div.logo").height(200);
$('div.logo a').css('background-image', 'url(img/logo-clear.png)');
} else {
$("div.logo").height(50);
$('div.logo a').css('background-image', 'url(img/logo-sm.png)');
}
});
});
Instead of changing css you can add and remove css, something like this
$(document).ready(function(){
$(document).scroll(function() {
if(window.innerWidth > 950){
if ($(document).scrollTop() < 25) {
$('.logo').addClass('logo-clear');
} else {
$('.logo').removeClass('logo-clear');
}
}
});
});
body{
height: 150vh;
}
.logo{
background-color: green;
width: 500px;
height: 500px;
}
.logo a{
height: 50px;
}
.logo.logo-clear{
background-color: yellow;
}
.logo.logo-clear a{
height: 200px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="logo">
hello
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Note, I added some additional css for visualization purpose. You can also check it here https://output.jsbin.com/viqebo
Just put your code inside a if condition which checks width of the window (if ($(window).width () > 950))
$(document).ready(function(){
//left side menu functions End
//Logo function
$(document).scroll(function() {
if ($(window).width () > 950) {
if ($(document).scrollTop() < 25) {
$("div.logo").height(200);
$('div.logo a').css('background-image', 'url(img/logo-clear.png)');
} else {
$("div.logo").height(50);
$('div.logo a').css('background-image', 'url(img/logo-sm.png)');
}
}
});
});

Backwards animation not working properly in Game

I'm trying to make a simple Javascript game which consists in a square expanding, while the player have to hit "A" to make it smaller. The goal is to make the square disappear and not to let the square engulf the whole screen.
But I'm experiencing three issues:
- When I hit A, the square stops expanding and starts getting smaller, but it never stops. It should only work for a about a second and then expand again.
- The pause button (enter) doesn't always work the way it should. I feel like it waits for the animation stop, but I don't want it to work like this.
- The square doesn't expand from the center.
The HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="styles/game.css"></link>
<script language="javascript" type="text/javascript" src="scripts/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="scripts/game.js"></script>
</head>
<body>
<section class="game">
<div id="game" style="position:absolute;"><img id="player" class="square"></img></div>
</section>
</body>
</html>
The Javascript:
//set update interval
setInterval(update, 10);
var isPlaying = false;
$(document).ready(function() {
});
function playerInput() {
$(document).keydown(function(event) {
if ( event.which == 65 ) {
if (isPlaying == true) {
$("#player").animate({height: '-=10', width: '-=10'}, 1);
}
} else if (event.which == 13) {
isPlaying = !isPlaying;
}
});
}
function update() {
playerInput();
if (isPlaying == true) {
$("#player").animate({height: '+=10', width: '+=10'}, 1);
}
}
The CSS:
body, html {
height: 1000px;
width: 1000px;
margin: auto;
background-color: black;
}
.game {
height: 800px;
width: 800px;
margin: auto;
margin-top: 10px;
background-color: black;
}
.square {
background-image: url("../images/square.png");
margin: 375px;
height: 30px;
width: 30px;
}

Categories