When the right arrow key is pressed I would like to increment the left position of a div by 10px using the style property. Here is my script and what I've tried so far:
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if (k.keyCode == RightBtn) {
document.getElementById("test").style.left = document.getElementById("test").style.left + 10px;
}
}
#test {
position: relative;
left: 0px;
width: 25px;
height: 80px;
background-color: black;
}
<div id="test"></div>
The style property of a DOM element is essentially a dictionary with string key-value pairs. It expects a CSS key, and a proper string value.
Your current code comes out as left: 10px10px and that doesn't make much sense for CSS.
In order for this to work, you'd have to regard the px.
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if (k.keyCode == RightBtn) {
var moveEl = document.getElementById("test"),
currLeft = parseInt(moveEl.style.left || 0);
moveEl.style.left = (currLeft + 10) + 'px';
}
}
#test {
position: relative;
left: 0px;
width: 25px;
height: 80px;
background-color: black;
}
<div id="test"></div>
Further reading and examples - HTMLElement.style
Remove px from 10.
if (k.keyCode == RightBtn) {
document.getElementById("test").style.left = document.getElementById("test").style.left + 10;
}
Try following way:
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if(k.keyCode == RightBtn) {
document.getElementById("test").style.left = parseInt(document.getElementById("test").style.left || 0) + 10 + 'px';
}
}
Related
I have this little block that I move around using javascript code. It works all good except if I keep moving it, it can easily get out of the box where it is supposed to be.
Can I prevent this somehow? So no matter how far I want to move it, it will stay stuck inside of the container/box ?
Here's my snippet code:
/// store key codes and currently pressed ones
var keys = {};
keys.UP = 38;
keys.LEFT = 37;
keys.RIGHT = 39;
keys.DOWN = 40;
/// store reference to character's position and element
var character = {
x: 100,
y: 100,
speedMultiplier: 2,
element: document.getElementById("character")
};
var is_colliding = function(div1, div2) {
var d1_height = div1.offsetHeight;
var d1_width = div1.offsetWidth;
var d1_distance_from_top = div1.offsetTop + d1_height;
var d1_distance_from_left = div1.offsetLeft + d1_width;
var d2_height = div2.offsetHeight;
var d2_width = div2.offsetWidth;
var d2_distance_from_top = div2.offsetTop + d2_height;
var d2_distance_from_left = div2.offsetLeft + d2_width;
var not_colliding =
d1_distance_from_top <= div2.offsetTop ||
div1.offsetTop >= d2_distance_from_top ||
d1_distance_from_left <= div2.offsetTop ||
div1.offsetLeft >= d2_distance_from_left;
return !not_colliding;
};
/// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var kc = e.keyCode || e.which;
keys[kc] = e.type == 'keydown';
};
/// character movement update
var moveCharacter = function(dx, dy){
character.x += (dx||0) * character.speedMultiplier;
character.y += (dy||0) * character.speedMultiplier;
character.element.style.left = character.x + 'px';
character.element.style.top = character.y + 'px';
};
/// character control
var detectCharacterMovement = function(){
if ( keys[keys.LEFT] ) {
moveCharacter(-5, 0);
}
if ( keys[keys.RIGHT] ) {
moveCharacter(5, 0);
}
if ( keys[keys.UP] ) {
moveCharacter(0, -5);
}
if ( keys[keys.DOWN] ) {
moveCharacter(0, 5);
}
};
/// update current position on screen
moveCharacter();
/// game loop
setInterval(function(){
detectCharacterMovement();
}, 1000/24);
body{
display: flex;
justify-content: center;
align-items: center;
}
#character {
position: absolute;
width: 42px;
height: 42px;
background: red;
z-index:99;
}
#container{
width: 400px;
height: 400px;
background: transparent;
border:5px solid rgb(0, 0, 0);
position: relative;
overflow: hidden;
}
<div id="container">
<div id="character"></div>
</div>
PS: You can move the box using keyboard arrows.
Get the container width and height into variable and set a condition on your move
var moveCharacter = function(dx, dy){
let div_width = document.getElementById('container').clientWidth;
let div_height = document.getElementById('container').clientHeight;
if((div_width - character.x) < 50 ){ // 50 = width of character and padding
character.x = div_width - 50;
}
if(character.x < 10){ // Padding
character.x = 11;
}
if((div_height - character.y) < 50 ){
character.y = div_height - 50;
}
if(character.y < 10){
character.y = 11;
}
I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)
I'm trying to recreate my own version of FlappyBird. You can see my game here: http://ps11.pstcc.edu/~c2375a22/lab6/lab6.html
The only problem that I've encountered is that none of my "blocks" are showing up. If you have never played FlappyBird, the blocks are objects that you must avoid in order to keep progressing throughout the game. If you touch a block, you lose.
My player controls are working and the collision system seems to be fine as well. Any ideas?
This is my code:
$(function () {
alert("Welcome to Space Dodge!"
+ "\n\nNavigate your vessel through the unknown for as long as you can!"
+ "\n\nUse 'Spacebar' to control the ship."
+ "\n\nIf the ship hits a block, the top, or the bottom, you lose!")
//Game variables
var game_area = $('#game_area');
var ship = $('#ship');
var block = $('.block');
var block1 = $('#block1');
var block2 = $('#block2');
var score = $('#score');
var restart_button = $('#restart_button');
//Set up variables
var game_width = parseInt(game_area.width());
var game_height = parseInt(game_area.height());
var block_initial_position = parseInt(block.css('right'));
var block_initial_height = parseInt(block.css('height'));
var ship_left = parseInt(ship.css('left'));
var ship_height = parseInt(ship.height());
//Starting speed - this will increase by +1 every time the player goes through a checkpoint
var speed = 10;
var go_up = false;
var update_score = false;
var game_over = false;
var the_game = setInterval(function () {
if (collision(ship, block1) || collision(ship, block2) || parseInt(ship.css('top')) <= 0 || parseInt(ship.css('top')) > game_height - ship_height) {
end_game();
alert("Game Over! \n\nClick 'Restart' to play again. ")
} else {
var block_current_position = parseInt(block.css('right'));
//Update the score when the poles have passed the bird successfully
if (block_current_position > game_width - ship_left) {
if (score_updated === false) {
score.text(parseInt(score.text()) + 1);
score_updated = true;
}
}
//Check whether the poles went out of the container
if (block_current_position > game_width) {
var new_height = parseInt(Math.random() * 100);
//Change the pole's height
block1.css('height', block_initial_height + new_height);
block2.css('height', block_initial_height - new_height);
//Increase speed,
speed = speed + 1;
score_updated = false;
pole_current_position = pole_initial_position;
}
//Move blocks
block.css('right', block_current_position + speed);
if (go_up === false) {
go_down();
}
}
}, 40);
//Determine collison domains
function collision($div1, $div2) {
//First set of axis
var x1 = $div1.offset().left;
var y1 = $div1.offset().top;
var h1 = $div1.outerHeight(true);
var w1 = $div1.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
//Second set of axis
var x2 = $div2.offset().left;
var y2 = $div2.offset().top;
var h2 = $div2.outerHeight(true);
var w2 = $div2.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;
// If the ship meets this condition, collision is false
if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
return true;
}
function go_down() {
ship.css('top', parseInt(ship.css('top')) + 5);
}
function up() {
ship.css('top', parseInt(ship.css('top')) - 10);
}
function end_game() {
clearInterval(the_game);
game_over = true;
}
$(document).on('keydown', function (e) {
var key = e.keyCode;
if (key === 32 && go_up === false && game_over === false) {
go_up = setInterval(up, 50);
}
});
$(document).on('keyup', function (e) {
var key = e.keyCode;
if (key === 32) {
clearInterval(go_up);
go_up = false;
}
});
//Reload the page and reset the game
restart_button.click(function () {
location.reload();
});
});
body {
height: 100%;
width: 100%;
margin: 0;
background-color: black;
}
#game_area {
position: relative;
height: 400px;
width: 90%;
border: 2px solid chartreuse;
background-color: black;
margin-top: 4%;
margin-bottom: 4%;
margin-left: 4%;
overflow: hidden;
}
#ship {
position: absolute;
background: url('ship.png');
height: 42px;
width: 65px;
background-size: contain;
background-repeat: no-repeat;
top: 20%;
left: 15%;
}
.block {
position: absolute;
height: 130px;
width: 50px;
background-color: chartreuse;
right: -50px;
}
#block1 {
top: 0;
}
#block2 {
bottom: 0;
}
#score_area {
text-align: center;
font-size: 40px;
color: chartreuse;
}
<body>
<!-- Game area on the page -->
<div class="container" id="game_area">
<div id="ship"></div>
<div id="block1"></div>
<div id="block2"></div>
</div>
<!-- Score section -->
<div class="container" id="score_area">
<P>Score: <span id="score">0</span></P>
</div>
<!-- Restart button -->
<div class="container" id="restart_area">
<center><button type="button" class="btn btn-primary"
id="restart_button">Restart</button></center>
</div>
<!-- Game script -->
<script src="lab6_game.js"></script>
</body>
</html>
Add the class block to... blocks :p
<div id="block1" class="block"></div>
<div id="block2" class="block"></div>
Instead of
<div id="block1" ></div>
<div id="block2" ></div>
Below is an example of a box moving left,right,up or down based
on pressing the arrow keys. However when I added a "laser" and used
the exact same principal/code to move the laser from left to right using "laserLeft++;" with the space bar, it does not move. I have very
carefully duplicated the code from the "square" to apply to the laser and
I cannot find why there is no movement. (I did not copy and paste the entire view source since it isn't relevant to problem).
the specific function is question is fireLaser().
#square {
position: absolute;
top: 0px;
left: 0px;
height: 5px;
width: 5px;
background-color: white;
}
#laser {
postion: absolute;
top: 0px;
left 0px;
height: 2px;
width: 5px;
background-color: red;
}
<script>
document.addEventListener("keydown", keyBoardInput);
var boxTop = 0;
var boxLeft = 0;
var laserTop = 0;
var laserLeft = 0;
function moveBoxUp(){
var square = document.getElementById("square");
boxTop--;
square.style.top = boxTop;
};
function moveBoxDown(){
var square = document.getElementById("square");
boxTop++;
square.style.top = boxTop;
};
function moveBoxLeft(){
var square = document.getElementById("square");
boxLeft--;
square.style.left = boxLeft;
};
function moveBoxRight(){
var square = document.getElementById("square");
boxLeft++;
square.style.left = boxLeft;
};
function fireLaser(){
var laser = document.getElementById("laser");
laserLeft++;
laser.style.left = laserLeft;
};
var i = event.keyCode;
if(i == 38){
moveBoxUp();
};
if(i == 40){
moveBoxDown();
};
if(i == 37){
moveBoxLeft();
};
if(i == 39){
moveBoxRight();
};
if (i == 32){
fireLaser();
};
};
</script>
I found my error!!! it was incorrectly typed "postion: absolute;" now it works perfectly!!!
I have a setInterval function that wont execute if the increment is less than 101ms. The timing will go any number above 100ms. I want to be able to increment the function by 10ms. offY and strtPos also become undefined when the timing goes below 101ms. How do I make it work the same as it is, but instead, have it incremented by 10ms?
var strtPos;
var offY;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 101); //<-- When I change that value to below 101, it prevents the code from working
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>
The short answer is you need to give offY a value that is not undefined initially, so I've rearranged the variables at the top of your code.
Originally, offY only gets a value after ~100ms (setInterval(st, 100)), and without a value that is not undefined the otherfunction's calculations won't work. So you needed the st function to execute first, hence requiring a value > 100.
var strtPos;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var offY = obj.offsetTop;
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 10);
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>