I'm learning how to develop a game in html/css3/javascript/jquery and i have to support multiple keyboard inputs.
By following a book, i have written this code:
var pingpong = {};
pingpong.pressedKeys = [];
$(function() {
// set interval to call gameloop every 30 milliseconds
pingpong.timer = setInterval(gameloop, 30);
// mark down what key is down and up into an array called
// "pressedKeys"
$(document).keydown(function(e) {
pingpong.pressedKeys[e.which] = true;
});
$(document).keyup(function(e) {
pingpong.pressedKeys[e.which] = false;
});
});
function gameloop() {
movePaddles();
}
function movePaddles() {
// use our custom timer to continuously check if a key is
// pressed.
if (pingpong.pressedKeys[KEY.UP]) {// arrow-up
// move the paddle B up 5 pixels
var top = parseInt($("#paddleB").css("top"));
$("#paddleB").css("top", top - 5);
}
if (pingpong.pressedKeys[KEY.DOWN]) {// arrow-down
// move the paddle B down 5 pixels
var top = parseInt($("#paddleB").css("top"));
$("#paddleB").css("top", top + 5);
}
if (pingpong.pressedKeys[KEY.W]) {// w
// move the paddle A up 5 pixels
var top = parseInt($("#paddleA").css("top"));
$("#paddleA").css("top", top - 5);
}
if (pingpong.pressedKeys[KEY.S]) {// s
// move the paddle A down 5 pixels
var top = parseInt($("#paddleA").css("top"));
$("#paddleA").css("top", top + 5);
}
}
But it does not work. I mean, the paddles don't move! Any idea?
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyGame</title>
<style>
#playground {
background: #e0ffe0;
width: 400px;
height: 200px;
position: relative;
overflow: hidden;
}
#ball {
background: #fbb;
position: absolute;
width: 20px;
height: 20px;
left: 150px;
top: 100px;
border-radius: 10px;
}
.paddle {
background: #bbf;
left: 50px;
top: 70px;
position: absolute;
width: 30px;
height: 70px;
}
#paddleB {
left: 320px;
}
</style>
</head>
<body>
<header>
<h1>Test</h1>
</header>
<div id="game">
<div id="playground">
<div id="paddleA" class="paddle"></div>
<div id="paddleB" class="paddle"></div>
<div id="ball"></div>
</div>
</div>
<footer>
This is an example of creating a Game.
</footer>
<script src="js/jquery-1.11.3.js"></script>
<script src="js/html5games.pingpong.js"></script>
</body>
</html>
MyGoal
Move with S (down) and W (up) the left paddle, and with arrow up (UP) and arrow down (down) the right paddle. If i press S AND arrow down, the left paddle must move up, and the right paddle must move down, AT THE SAME TIME. (The events must not stop each other).
What i get
The keyboard input does not work. The paddles don't move.
UPDATE
I forgot to add this to the .js code:
var KEY = {
UP : 38,
DOWN : 40,
W : 87,
S : 83
};
Related
I have successfully yoinked the code using javascript to replace the cursor with an animated gif from this page (https://css-tricks.com/using-css-cursors/). I have successfully chucked her into Dreamweaver, I'm new to coding and I know it's way too much to start with but I want to make my website track the location of your cursor and change depending on which half of the page it's on. To be specific cursors derived from the painting: the creation of adam (the hands). Depending on which side it will switch between one of two cursors. I have found success in using a singular png as the cursor with the cursor: url() CSS method. This current method uses the CSS method of cursor: none in my style.css file.
The current javascript code is as follows
(function() {
var follower, init, mouseX, mouseY, positionElement, printout, timer;
follower = document.getElementById('follower');
printout = document.getElementById('printout');
mouseX = (event) => {
return event.clientX;
};
mouseY = (event) => {
return event.clientY;
};
positionElement = (event) => {
var mouse;
mouse = {
x: mouseX(event),
y: mouseY(event)
};
follower.style.top = mouse.y + 'px';
return follower.style.left = mouse.x + 'px';
};
timer = false;
window.onmousemove = init = (event) => {
var _event;
_event = event;
return timer = setTimeout(() => {
return positionElement(_event);
}, 1);
};
}).call(this);
and the style.css file is:
html {
cursor: url("Cursor222.png");
background: #E0CDA9;
}
#follower {
position: absolute;
top: 50%;
left: 50%;
}
#follower #circle1 {
position: absolute;
background: #0004D9;
border-radius: 50%;
height: 0em;
width: 0em;
margin-top: 0em;
margin-left: 0em;
}
#follower #circle2 {
position: absolute;
background: rgba(200,0,0,0.8);
border-radius: 50%;
height: 0em;
width: 0em;
margin-top: 0em;
margin-left: 0em;
}
I'm very new to CSS and javascript, I don't know the way to implement conditional terms like if and else, can someone chuck me some support. I get it's a big ask and I can compensate you for your time.
Here is a sample using an image:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.cursor-left {
/* cursor: url('url-to-image-1'), auto; */ // Add your cursor here
cursor: pointer;
}
.cursor-right {
/* cursor: url('url-to-image-2'), auto; */ // Add your cursor here
cursor: cell;
}
</style>
</head>
<body>
<img src="https://uploads1.wikiart.org/images/michelangelo/sistine-chapel-ceiling-creation-of-adam-1510.jpg" id="container" />
<script>
const containerElement = document.querySelector('#container');
containerElement.addEventListener('mousemove', e => {
const imageWidth = containerElement.width;
// const windowWidth = window.innerWidth; // for window
if (e.clientX <= imageWidth / 2) {
containerElement.classList.remove('cursor-right');
containerElement.classList.add('cursor-left');
} else {
containerElement.classList.remove('cursor-left');
containerElement.classList.add('cursor-right');
}
});
</script>
</body>
</html>
If you want to do it with the whole page and not a specific container, attach the event listener to the document(body might not work for you, you can see why here) and track the width with the commented code. You can add as much cursor styles as you like by altering the mouse tracking constraints.
I am beginner to JS and I am trying to create a simple game in it. I am looking for a way to stop the player (20px x 20px) box causing the screen to scroll, i am looking for a fixed screen where the player cannot exceed the sides of the screen. Please see previous attempts below.
HTML :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="Style.css">
</head>
<body>
<div id="player"></div>
<script type="text/javascript" src="Script.js"></script>
</body>
</html>
CSS:
body{
margin: 0;
padding: 0;
background-color: red;
}
#player{
border-radius: 30%;
padding: 0px;
margin: 0px;
background-color: white;
width: 20px;
height: 20px;
position: absolute;
}
JavaScript:
var player = document.getElementById("player")
var pros = {'top': 0, 'left': 0, 'speed': 10}
var ws = {'h': screen.height, 'w': screen.width}
document.addEventListener("keydown", function(event){
var keyP = event.key;
if(keyP === "ArrowDown"){
pros.top = pros.top + pros.speed;
}else if(keyP === "ArrowUp"){
pros.top = pros.top - pros.speed;
}else if(keyP === "ArrowLeft"){
pros.left = pros.left - pros.speed;
}else if(keyP === "ArrowRight"){
pros.left = pros.left + pros.speed;
}
if(pros.top < 0){
pros.top = 0;
}else if(pros.top > ws.h){
pros.top = ws.h;
}else if(pros.left < 0){
pros.left = 0;
}else if(pros.left > ws.w){
pros.left = ws.w;
}
player.style.top = `${pros.top}px`;
player.style.left = `${pros.left}px`;
});
Now, I want the element to never escape the given screen area. As you can see in the code that I have tried to use screen.height/screen.width to control it but still it escapes the area and the scroll bars get activated even in the full screen mode. It looks too messy for a game.
Here is picture of how it escapes the area:
In Full Screen Mode :
Without Full Screen Mode :
The most accurate position and dimensions measurements are available via the getBoundingClientRect() function.
So at the top of your keystroke callback I'd add two lines:
var screenRect = document.body.getBoundingClientRect();
var playerRect = player.getBoundingClientRect();
These need to be calculated at every iteration in order to make sure that the "game" adapts to every screen change. Also any position increments are better calculated in percents of the screen size rather than static pixel values.
Your screen edge check should be rewritten like this:
if(playerRect.top < 0){
pros.top = 0;
} else if(playerRect.top + playerRect.height > screenRect.height){
// make sure the bottom edge of the player doesn't go over the bottom edge of the screen
pros.top = screenRect.height - playerRect.height;
}
if(playerRect.left < 0){
pros.left = 0;
} else if(playerRect.left + playerRect.width + > screenRect.width){
// make sure the right edge of the player doesn't go over the right edge of the screen
pros.left = screenRect.width - playerRect.width;
}
On the CSS side, try the following:
body{
margin: 0;
padding: 0;
background-color: red;
width: 100vw;
height: 100vh;
overflow: hidden;
}
#player{
border-radius: 30%;
padding: 0px;
margin: 0px;
background-color: white;
width: 20px;
height: 20px;
position: fixed;
}
The height and width of your PLAYER object is 20px as concluded from the Stylesheet that you have provided.
If you place your element on a 2D plane, then it's coordinates will be the point where its TOP-LEFT corner lie. Focus here.
So, your JavaScript should change to this:
...
if(pros.top < 0){
pros.top = 0;
}else if(pros.top > ws.h-20){ // changed here
pros.top = ws.h-20; // try playing with the value here
}else if(pros.left < 0){
pros.left = 0;
}else if(pros.left > ws.w-20){ //changed here
pros.left = ws.w-20; // try playing with the value here
}
...
This would always place the #player element 20px inside on the horizntal axis and 20px on the vertical axis. I was successful in limiting the appearance of the horizontal scroll-bar but the vertical vanished only for a value of ws.h-40.
Hope this helps.
Hey :) Maybe this helps you:
<style type="text/css">
body {
overflow:hidden;
}
</style>
Setting the overflow: hidden will hide the scrollbar.
I am trying to make some 2d game with javascript, html and css.
This is just a start but it seems like I have some weird problem.
When I move up I move my player block up and scroll top but scroll top is scrolling more then player block moved.
I am getting player block position to move up with 50px and document scrollTop position to move up same 50px by subscription.
$(document).ready(function() {
//map info
var $map = $('#map'),
viewportWidth = +$(window).width(),
viewportHeight = +$(window).height(),
mapWidth = +$map.width(),
mapHeight = +$map.width();
//player info
var $player = $('.player').eq(0);
//Adding some logic
//Half height and width of map and half of viewport to center it
var halfMW = mapWidth / 2,
halfMH = mapHeight / 2,
halfVW = viewportWidth / 2,
halfVH = viewportHeight / 2;
//Now we need to get subsrtiction of half map width and half viewport width
//and same for height
var mapPositionX = halfMW - halfVW,
mapPositionY = halfMH - halfVH;
//Now we need to put map in negative values so the viewport stands in the center
//Css example
/*
$map.css({
'top': '-' + mapPositionY + 'px',
'left': '-' + mapPositionX + 'px'
});
*/
//Scroll example
$(document).scrollLeft(mapPositionX);
$(document).scrollTop(mapPositionY);
//moving player
$(document).keydown( function(key) {
console.log(key.which);
//down - 40
//right - 39
//up - 38
//left - 37
if(key.which === 38) {
var posUP = +$player.css("top").replace("px", "");
$player.css('top', posUP-50+'px');
$(document).scrollTop($(document).scrollTop() - 50);
}
});
});
html, body {
margin: 0;
padding: 0;
}
#map {
width: 10000px;
height: 10000px;
background: #71D014;
position: relative;
overflow: scroll;
}
.blocks {
width: 100px;
height: 100px;
position: absolute;
top: 4950px;
left: 4950px;
background: orange;
}
.player {
width: 50px;
height: 50px;
position: absolute;
top: 5050px;
left: 5050px;
background: #005ED2;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tanks</title>
<link rel="stylesheet" href="css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="map">
<div class="blocks"></div>
<div class="player"></div>
</div>
<script src="js/main.js"></script>
</body>
</html>
I found out what was the problem.
Well up, down, left and right arrows on keyboard are set as defaults for moving scroll x and y and I just needed to add preventDefault(); on start.
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;
}
I have posted my problem at http://jsfiddle.net/ugnf4/ as it would be make it easier.
Below is my html / javascript code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="mainContainer">
<div id="pageContainer" style="background: #cdcdcd;"></div>
</div>
<style>
BODY {
margin: 0px;
padding: 0px;
}
#pageContainer {
position: relative;
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
border: 1px solid #000000;
}
#mainContainer {
width: 100%;
overflow: hidden;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script type="text/javascript">
$(document).ready(function() {
setHeight();
$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
});
</script>
</body>
</html>
Currently #mainContainer div has overflow hidden as i dont want to show scroll bars and #pageContainer div (inner div) is scaled at 1.37 using css3, as in certain cases based on screen / browser width height #pageContainer's content would be hidden because of overflow hidden.
I want to code javascript so that if somebody moves cursor in #mainContainer, based on position of mouse X and Y co-ordinates I would like to move #pageContainer so that similar position of #pageContainer would be visible (I hope it is clear).
I m having problem as I m using -webkit-transform-origin, unable to understand how to move #pageContainer around with respect to mouse co-ordinates of #mainContainer.
UPDATE:
I m looking something like what happens in issuu.com website when you open an ebook and zoom it more than the browser size (Should make it more clear)
I m looking for algo or pointer how to achieve it (how to calculate it) not necessarily a working script.
How can this be achieved.
Below is working html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="mainContainer">
<div id="pageContainer" >
<div id="pageContainerInner"style="background: #cdcdcd;">
</div>
</div>
<style>
BODY {
margin: 0px;
padding: 0px;
}
#pageContainer {
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
}
#mainContainer {
width: 100%;
overflow: hidden;
}
#pageContainerInner {
position: relative;
width: 1218px;
height: 774px;
border: 1px solid #000000;
top: 0;
left: 0;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script type="text/javascript">
var pageWidth = 1220;
var pageHeight = 776;
var scale = 1.37;
var scaledDelta = 5; //Percentage mouse position approximation
$(document).ready(function() {
setHeight();
$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
// Calculate the offset of scaled Div
var offsetX = $('#pageContainer').offset().left;
var offsetY = $('#pageContainer').offset().top;
// Calculate div origin with respect to screen
var originX = (-1 * offsetX) / scale;
var originY = (-1 * offsetY) / scale;
var wWdt = $(window).width();
var wHgt = $(window).height();
// Now convert screen positions to percentage
var perX = e.pageX * 100 / wWdt;
var perY = e.pageY * 100 / wHgt;
// Div content which should be visible
var pageX = perX * pageWidth / 100;
var pageY = perY * pageHeight / 100;
// Calculate scaled divs new X, Y offset
var shiftX = (originX - pageX) + (e.pageX / scale);
var shiftY = (originY - pageY) + (e.pageY / scale);
$('#pageContainerInner').css({'left': shiftX+'px', 'top': shiftY+'px'});
});
</script>
</body>
</html>
Hope this will help others.
I have posted a probable solution at http://jsfiddle.net/PYP8c/.
Below are the modified styles for your page.
BODY {
margin: 0px;
padding: 0px;
}
#mainContainer {
width: 100%;
overflow: hidden;
position: relative;
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
border: 1px solid #000000;
}
#pageContainer {
position:absolute;
top:0px;
}
This is the javascript code for the same.
$(document).ready(function() {
//setHeight();
//$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
var contentHeight = $("#pageContainer").height();
var minTop = 774 - contentHeight;
if(minTop>0)
minTop = 0;
var currTop = ((e.pageY-10)/774.0)*(minTop);
document.getElementById("pageContainer").style.top = currTop+'px';
});
Its just a demo on how you could get the text to move based on the mouse coordinates.
You could make a lot of changes, like adding a scrollbar that fades which gives the user a feedback about how much content is still available in both the vertical directions.
Also I have used hard coded values for height, but in your final version I would recommend you get the height of the mainContainer division dynamically.