how do I make this element move backwards? - javascript

how do I stop the following interval and make the alien move backwards when it reaches 700px? I know I can do this with CSS but I want to do this strictly with JS. I don't understand how to stop the interval once it reaches the 700px left...
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
alien.style.left = left + 2 + "px";
}
interval = setInterval(flow, 10);
function stop() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) {
clearInterval(interval);
alien.style.left = left - 10 + "px";
}
};
setInterval(stop, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
}
<div class="game">
</div>
Any help?

Introduce a speed variable which will switch from 2 to -2 when it reaches the right limit. You should then do the same at the left side, and switch the speed from -2 to 2 again.
As you want to keep moving, the stop function is no longer needed.
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";
let speed = 2;
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) speed = -2;
else if (left <= 0) speed = 2;
alien.style.left = left + speed + "px";
}
interval = setInterval(flow, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
}
<div class="game">
</div>

To move your element you use left + 2 so it always is moving to one direction.
So when reaching 700px mark you should reverse it to be left - 2 until it's 0.
I have modified your code adding currentDirection variable
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
var currentDirection = 1;
var hasMoved = false;
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
alien.style.left = (left + 2 * currentDirection) + "px";
}
interval = setInterval(flow, 10);
function stop() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) {
currentDirection = -1;
} else if (left < 0) {
currentDirection = 1;
}
};
setInterval(stop, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
background: gold;
height: 20px;
width: 20px;
}
.alien {
background: red;
height: 20px;
width: 20px;
position: absolute;
}
<div class="game">
</div>

Related

Not able to get the input text box editable inside animated javascript

I have added the code snippet over here. I was trying to do some random exercise. Can someone look why my textbox is not editable. There is falling leaf animation over here. Along with I have added one textbox on top of it. But currently I am not able to add any text to the textbox.
I am just adding more text in order to overcome the error message that the post is mostly having code and not much explanation.
var LeafScene = function(el) {
this.viewport = el;
this.world = document.createElement('div');
this.leaves = [];
this.options = {
numLeaves: 20,
wind: {
magnitude: 1.2,
maxSpeed: 12,
duration: 300,
start: 0,
speed: 0
},
};
this.width = this.viewport.offsetWidth;
this.height = this.viewport.offsetHeight;
// animation helper
this.timer = 0;
this._resetLeaf = function(leaf) {
// place leaf towards the top left
leaf.x = this.width * 2 - Math.random()*this.width*1.75;
leaf.y = -10;
leaf.z = Math.random()*200;
if (leaf.x > this.width) {
leaf.x = this.width + 10;
leaf.y = Math.random()*this.height/2;
}
// at the start, the leaf can be anywhere
if (this.timer == 0) {
leaf.y = Math.random()*this.height;
}
// Choose axis of rotation.
// If axis is not X, chose a random static x-rotation for greater variability
leaf.rotation.speed = Math.random()*10;
var randomAxis = Math.random();
if (randomAxis > 0.5) {
leaf.rotation.axis = 'X';
} else if (randomAxis > 0.25) {
leaf.rotation.axis = 'Y';
leaf.rotation.x = Math.random()*180 + 90;
} else {
leaf.rotation.axis = 'Z';
leaf.rotation.x = Math.random()*360 - 180;
// looks weird if the rotation is too fast around this axis
leaf.rotation.speed = Math.random()*3;
}
// random speed
leaf.xSpeedVariation = Math.random() * 0.8 - 0.4;
leaf.ySpeed = Math.random() + 1.5;
return leaf;
}
this._updateLeaf = function(leaf) {
var leafWindSpeed = this.options.wind.speed(this.timer - this.options.wind.start, leaf.y);
var xSpeed = leafWindSpeed + leaf.xSpeedVariation;
leaf.x -= xSpeed;
leaf.y += leaf.ySpeed;
leaf.rotation.value += leaf.rotation.speed;
var t = 'translateX( ' + leaf.x + 'px ) translateY( ' + leaf.y + 'px ) translateZ( ' + leaf.z + 'px ) rotate' + leaf.rotation.axis + '( ' + leaf.rotation.value + 'deg )';
if (leaf.rotation.axis !== 'X') {
t += ' rotateX(' + leaf.rotation.x + 'deg)';
}
leaf.el.style.webkitTransform = t;
leaf.el.style.MozTransform = t;
leaf.el.style.oTransform = t;
leaf.el.style.transform = t;
// reset if out of view
if (leaf.x < -10 || leaf.y > this.height + 10) {
this._resetLeaf(leaf);
}
}
this._updateWind = function() {
// wind follows a sine curve: asin(b*time + c) + a
// where a = wind magnitude as a function of leaf position, b = wind.duration, c = offset
// wind duration should be related to wind magnitude, e.g. higher windspeed means longer gust duration
if (this.timer === 0 || this.timer > (this.options.wind.start + this.options.wind.duration)) {
this.options.wind.magnitude = Math.random() * this.options.wind.maxSpeed;
this.options.wind.duration = this.options.wind.magnitude * 50 + (Math.random() * 20 - 10);
this.options.wind.start = this.timer;
var screenHeight = this.height;
this.options.wind.speed = function(t, y) {
// should go from full wind speed at the top, to 1/2 speed at the bottom, using leaf Y
var a = this.magnitude/2 * (screenHeight - 2*y/3)/screenHeight;
return a * Math.sin(2*Math.PI/this.duration * t + (3 * Math.PI/2)) + a;
}
}
}
}
LeafScene.prototype.init = function() {
for (var i = 0; i < this.options.numLeaves; i++) {
var leaf = {
el: document.createElement('div'),
x: 0,
y: 0,
z: 0,
rotation: {
axis: 'X',
value: 0,
speed: 0,
x: 0
},
xSpeedVariation: 0,
ySpeed: 0,
path: {
type: 1,
start: 0,
},
image: 1
};
this._resetLeaf(leaf);
this.leaves.push(leaf);
this.world.appendChild(leaf.el);
}
this.world.className = 'leaf-scene';
this.viewport.appendChild(this.world);
// set perspective
this.world.style.webkitPerspective = "400px";
this.world.style.MozPerspective = "400px";
this.world.style.oPerspective = "400px";
this.world.style.perspective = "400px";
// reset window height/width on resize
var self = this;
window.onresize = function(event) {
self.width = self.viewport.offsetWidth;
self.height = self.viewport.offsetHeight;
};
}
LeafScene.prototype.render = function() {
this._updateWind();
for (var i = 0; i < this.leaves.length; i++) {
this._updateLeaf(this.leaves[i]);
}
this.timer++;
requestAnimationFrame(this.render.bind(this));
}
// start up leaf scene
var leafContainer = document.querySelector('.falling-leaves'),
leaves = new LeafScene(leafContainer);
leaves.init();
leaves.render();
body, html {
height: 100%;
}
form {
width: 600px;
margin: 0px auto;
padding: 15px;
}
input[type=text] {
display: block;
padding: 10px;
box-sizing: border-box;
font-size: x-large;
margin-top: 25%;
}
input[type=text] {
width: 100%;
margin-bottom: 15px;
}
.falling-leaves {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 100%;
max-width: 880px;
max-height: 880px; /* image is only 880x880 */
transform: translate(-50%, 0);
border: 20px solid #fff;
border-radius: 50px;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/125707/sidebar-bg.png) no-repeat center center;
background-size: cover;
overflow: hidden;
}
.leaf-scene {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 100%;
transform-style: preserve-3d;
}
.leaf-scene div {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/125707/leaf.svg) no-repeat;
background-size: 100%;
transform-style: preserve-3d;
backface-visibility: visible;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
</head>
<body>
<div class="falling-leaves">
<form id="frmContact">
<input type="text" id="txtName" name="txtName" placeholder="Text goes here">
</form>
</div>
<script src="script/script.js"></script>
</body>
</html>

Clearinterval method is unable to clear Rotation javascript animation

I am new to JS and i am trying to move object from left to right while spinning clockwise, here i applied setinterval for movement animation from left to right and also for rotation. I am able to clearinterval Movement from left to right but unable to clearinterval my Rotation i don't know why please if you can take a look
window.topPos = '';
var e = document.getElementById("aDiv");
var s = 1;
var rotate = false;
var degrees = 0;
function myInterval() {
var eLeftPos = e.offsetLeft;
e.style.left = (eLeftPos + s) + 'px';
function rot() {
degrees++;
e.style.transform = 'rotate(' + degrees + 'deg)';
}
var rotID = setInterval(rot, 1000)
var leftPos = (eLeftPos + s) >= 1000
if ((eLeftPos + s) >= 1000) {
clearInterval(rotID)
console.log(rotID)
}
if ((eLeftPos + s) >= 1000) {
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
#aDiv {
background: black;
width: 80px;
height: 80px;
position: relative;
}
#aDiv1 {
background: red;
width: 80px;
height: 80px;
position: absolute;
}
<div id="aDiv"></div>
<button>Stop</button>
You're unable to clear the interval from the rotation, because you start a new setInterval every time the first (movement) interval executes. You'll have a new rotation interval every 1000ms. Why not just move and rotate within the same setInterval callback and then theres only 1 to cancel:
window.topPos = '';
var e = document.getElementById("aDiv");
var s = 1;
var rotate = false;
var degrees = 0;
function myInterval() {
var eLeftPos = e.offsetLeft;
var leftPos = (eLeftPos + s); // new left pos
e.style.left = leftPos + 'px';
degrees++;
e.style.transform = 'rotate(' + degrees + 'deg)';
if (leftPos >= 100) { // made 100 just to show the effect quicker
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
#aDiv {
background: black;
width: 80px;
height: 80px;
position: relative;
}
#aDiv1 {
background: red;
width: 80px;
height: 80px;
position: absolute;
}
<div id="aDiv"></div>
<button>Stop</button>

how to resize div after rotating it (is it possible to modify the mouse event coordinates based on the rotation?)

there are 8 nodes around a div which can resize the div in 8 directions, when the div is not rotated, they can resize properly. However, when the div is rotated, for example, 90 degrees clockwise, then the behavior is weird, since the mouse event is different with the rotated div.
i've checked these but didn't help:
Logic to set fixed corner while resize after rotate?
How to resize with fixed corner after rotate?
i made a demo here: https://output.jsbin.com/nobasavaza
any ideas?
```
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#cut {
opacity: 0.6;
height: 150px;
width: 150px;
position: absolute;
top: 150px;
left: 150px;
cursor: pointer;
border: 1px dotted red;
}
.box-resize {
border: 1px solid black;
width: 4px;
height: 4px;
position: absolute;
}
.box-top-left {
top: -3px;
left: -3px;
cursor: nw-resize;
}
.box-top-right {
top: -3px;
right: -3px;
cursor: ne-resize;
}
.box-left-center {
top: 50%;
left: -3px;
cursor: w-resize;
}
.box-right-center {
top: 50%;
right: -3px;
cursor: e-resize;
}
.box-bottom-left {
left: -3px;
bottom: -3px;
cursor: sw-resize;
}
.box-bottom-right {
right: -3px;
bottom: -3px;
cursor: se-resize;
}
.box-top-center {
left: 50%;
top: -3px;
cursor: n-resize;
}
.box-bottom-center {
left: 50%;
bottom: -3px;
cursor: s-resize;
}
</style>
</head>
<body>
<input type="text" id="rotate_degree" placeholder="degree in closewise">
<button id="rotate_submit">rorate</button>
<div id="cut">
hello
<div class="box-resize box-top-left"></div>
<div class="box-resize box-top-right"></div>
<div class="box-resize box-left-center"></div>
<div class="box-resize box-right-center"></div>
<div class="box-resize box-bottom-left"></div>
<div class="box-resize box-bottom-right"></div>
<div class="box-resize box-top-center"></div>
<div class="box-resize box-bottom-center"></div>
</div>
<script>
window.onload = function () {
var resize = document.getElementsByClassName("box-resize");
var cut = document.getElementById("cut");
var cutWidth = 0;
var cutHeight = 0;
var startX = 0;
var startY = 0;
var top = 0;
var left = 0;
var dir = "";
for (var i = 0; i < resize.length; i++) {
resize[i].onmousedown = function (e) {
startX = e.clientX;
startY = e.clientY;
cutWidth = cut.offsetWidth;
cutHeight = cut.offsetHeight;
top = cut.offsetTop;
left = cut.offsetLeft;
var className = this.className;
if (className.indexOf("box-right-center") > -1) {
dir = "E";
}
else if (className.indexOf("box-top-left") > -1) {
dir = "NW";
}
else if (className.indexOf("box-top-right") > -1) {
dir = "NE";
}
else if (className.indexOf("box-left-center") > -1) {
dir = "W";
}
else if (className.indexOf("box-bottom-left") > -1) {
dir = "SW";
}
else if (className.indexOf("box-bottom-right") > -1) {
dir = "SE";
}
else if (className.indexOf("box-bottom-center") > -1) {
dir = "S";
}
else if (className.indexOf("box-top-center") > -1) {
dir = "N";
}
document.addEventListener('mousemove', test);
e.preventDefault();
}
}
document.onmouseup = function (e) {
dir = "";
document.removeEventListener('mousemove', test);
e.preventDefault();
}
function test(e) {
var width = e.clientX - startX;
var height = e.clientY - startY;
if (dir == "E") {
cut.style.width = cutWidth + width + "px";
}
else if (dir == "S") {
cut.style.height = cutHeight + height + "px";
}
else if (dir == "N") {
if (height < cutHeight) {
cut.style.height = cutHeight - height + "px";
cut.style.top = top + height + "px";
}
}
else if (dir == "W") {
if (width < cutWidth) {
cut.style.width = cutWidth - width + "px";
cut.style.left = left + width + "px";
}
}
else if (dir == "NW") {
if (width < cutWidth && height < cutHeight) {
cut.style.width = cutWidth - width + "px";
cut.style.height = cutHeight - height + "px";
cut.style.top = top + height + "px";
cut.style.left = left + width + "px";
}
}
else if (dir == "NE") {
if (height < cutHeight) {
cut.style.width = cutWidth + width + "px";
cut.style.height = cutHeight - height + "px";
cut.style.top = top + height + "px";
}
}
else if (dir == "SW") {
if (width < cutWidth) {
cut.style.width = cutWidth - width + "px";
cut.style.height = cutHeight + height + "px";
cut.style.left = left + width + "px";
}
}
else if (dir == "SE") {
if (width < cutWidth) {
cut.style.width = cutWidth + width + "px";
cut.style.height = cutHeight + height + "px";
}
}
}
}
document.getElementById('rotate_submit').addEventListener('click', function () {
const degree = document.getElementById('rotate_degree');
document.getElementById("cut").style.transform = 'rotate(' + degree.value + 'deg)';
})
</script>
</body>
</html>
```

trail without a canvas

I've created the following code and I would like to have a trail following the dropped ball.
JSFiddle: https://jsfiddle.net/uj896hmq/72/
Code
var generateGame = function(){
var string = "";
var discAmount = 0;
for(var x = 0; x < 13; x++){
discAmount++;
string += "<div class='row'>";
for(var y = 1; y <= discAmount; y++){
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function(){
startGame();
});
var startGame = function(){
var $board = $('.board .wrapper'),
$el = $(".falling");
var currentRow = 0,
path = generatePath();
setInterval(function(){
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow]),
top = getPosition.position().top,
left = getPosition.position().left;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}, 500);
}
var generatePath = function(){
var path = [0];
for(var x = 1; x < 13; x++){
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
console.log(generatePath());
Point is I have no idea how I would achieve this with regular javascript and or jQuery, I thought of maybe placing a lot of divs at the position of the ball but that didn't seem proper.
Anyone has any ideas?
You can use SVG to dynamically add lines to the HTML without canvas. I've created a crude example that you can refer to. Basically it is just some calculations to position the lines.
var generateGame = function() {
var string = "";
var discAmount = 0;
for (var x = 0; x < 13; x++) {
discAmount++;
string += "<div class='row'>";
for (var y = 1; y <= discAmount; y++) {
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function() {
startGame();
});
var startGame = function() {
var $board = $('.board .wrapper'),
$el = $(".falling"),
$trail = $('.trail'),
$prevDisc = null;
var currentRow = 0,
path = generatePath();
$trail.empty();
setInterval(function() {
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow])
if (getPosition.length > 0) {
var top = getPosition.position().top,
left = getPosition.position().left;
if ($prevDisc) {
var isLeft = left < $prevDisc.position().left;
drawPath($prevDisc.position().left, currentRow - 1, isLeft);
}
$prevDisc = getPosition;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}
}, 500);
}
var generatePath = function() {
var path = [0];
for (var x = 1; x < 13; x++) {
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function drawPath(xPos, prevRow, isLeft) {
if (prevRow >= 0) {
var svgTopOffSet = 12;
var svgHeight = 22;
var svgWidth = 22;
var $trail = $('.trail');
var $newTrail = $(document.createElementNS('http://www.w3.org/2000/svg', 'svg'));
$newTrail.attr({
x: xPos,
y: prevRow * svgHeight + svgTopOffSet
});
var $line = $(document.createElementNS('http://www.w3.org/2000/svg', 'line'));
$line.attr({
x1: svgWidth / 2,
y1: 0,
x2: isLeft ? 0 : svgWidth,
y2: svgWidth,
style: 'stroke:orange;stroke-width:3'
});
$newTrail.append($line);
$trail.append($newTrail);
}
}
body {
background: rgb(26, 30, 35);
}
.board {
width: 500px;
height: 300px;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
}
.row {
display: flex;
justify-content: center;
}
.row .disc {
height: 6px;
width: 6px;
border-radius: 50%;
background: gray;
margin: 8px;
}
.wrapper .falling {
position: absolute;
height: 11px;
width: 11px;
border-radius: 50%;
background: orange;
transform: translate(50%, 50%);
z-index: 1;
}
.wrapper {
position: relative;
}
.trail {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
line { stroke-dasharray: 25; stroke-dashoffset: 25; animation: offset 0.5s linear forwards; }
#keyframes offset {
to {
stroke-dashoffset: 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='board'>
<div class='wrapper'>
<svg class="trail">
</svg>
</div>
<button>
test game
</button>
</div>

How to make my random generated div appear inside container div?

HTML
<div id="container">
<div id="wrapper">
</div>
<span id = "waveNum">Current Wave: 0</span>
<input type = "button" value = "Start Game" onclick = "startGame()"></input>
</div>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="main.js"></script>
</body>
Javascript
var keyArray = [];
var currentWave = 1;
var player;
var player2;
function initiate(){
player = new createPlayer(150,50,"player1","relative","blue");
player2 = new createPlayer(150,0,"player2","relative","green");
}
function startGame() {
point();
}
function createPlayer(l,t,id,pos,color){
this.speed = 3;
this.width = 25;
this.height = 25;
this.left = l;
this.top = t;
this.id = id;
this.model = $("<div id=" + id + "/>")
.css({"backgroundColor":color,"height":this.height,"width":this.width,
"left":this.left,"top":this.top,"position":pos})
$('#wrapper').append($(this.model));
}
function point(){
leftP = parseInt(Math.random()*970);
topP = parseInt(Math.random()*580);
$points = $("<div class=point/>")
.css({"backgroundColor":"yellow","height":"10px","width":"10px","left":0,
"top":0,"position":"relative"})
$('#wrapper').append($points)
}
function update(){
//left
if(keyArray[65]){
var newLeft = parseInt(player.left)-player.speed+"px"
player.left = newLeft;
document.getElementById(player.id).style.left = newLeft;
}
//right
if(keyArray[68]){
var newLeft = parseInt(player.left)+player.speed+"px"
player.left = newLeft;
document.getElementById(player.id).style.left = newLeft;
}
//up
if(keyArray[87]){
var newTop = parseInt(player.top)-player.speed+"px"
player.top = newTop;
document.getElementById(player.id).style.top = newTop;
}
//down
if(keyArray[83]){
var newTop = parseInt(player.top)+player.speed+"px"
player.top = newTop;
document.getElementById(player.id).style.top = newTop;
}
//player2
//left
if(keyArray[37]){
var newLeft = parseInt(player2.left)-player2.speed+"px"
player2.left = newLeft;
document.getElementById(player2.id).style.left = newLeft;
}
//right
if(keyArray[39]){
var newLeft = parseInt(player2.left)+player2.speed+"px"
player2.left = newLeft;
document.getElementById(player2.id).style.left = newLeft;
}
//up
if(keyArray[38]){
var newTop = parseInt(player2.top)-player2.speed+"px"
player2.top = newTop;
document.getElementById(player2.id).style.top = newTop;
}
//down
if(keyArray[40]){
var newTop = parseInt(player2.top)+player2.speed+"px"
player2.top = newTop;
document.getElementById(player2.id).style.top = newTop;
}
blockade();
requestAnimationFrame(update);
}
function blockade(){
var elemLeft = parseInt($('#wrapper').css('left'));
var elemWidth = parseInt($('#wrapper').css('width'));
var elemTop= parseInt($('#wrapper').css('height'));
//blocks players from moving outside of game
if(parseInt(player.left) + player.width >= elemLeft+elemWidth){
player.left = elemWidth - player.width - 2;
}
if(parseInt(player.top) + player.height >= elemTop){
player.top = elemTop - player.height - 2;
}
if(parseInt(player.top) < 3){
player.top = 3;
}
if(parseInt(player.left) < 3){
player.left = 3;
}
if(parseInt(player2.left) + player2.width >= elemLeft+elemWidth){
player2.left = elemWidth - player2.width - 2;
}
if(parseInt(player2.top) + player2.height >= elemTop){
player2.top = elemTop - player2.height - 2;
}
if(parseInt(player2.top) < 3){
player2.top = 3;
}
if(parseInt(player2.left) < 3){
player2.left = 3;
}
}
window.onkeydown = function(page){
keyArray[page.keyCode] = page.type === 'keydown';
}
window.onkeyup = function(page){
keyArray[page.keyCode] = page.type === 'keydown'
}
CSS
html, body {margin: 0; height: 100%; overflow: hidden}
#container{
width:80%;
height:60%;
display: block;
text-align:center;
margin: 0 auto;
}
#wrapper{
left:0px;
width:1000px; /* 100% */
height:600px;
border:1px solid lime;
margin:0 auto;
background-color:black;
}
#player1, .point {
float: left;
clear: both;
}
body{
background-color:black;
}
#waveNum{
color:white;
font-size:200%;
}
.point {
overflow: auto;
}
So currently I need my point() function to generate a random div within the <div id="wrapper"> which it is but after a few different spawns, does not stay within the wrapper div eventually. It seems like the container of the point() seems to be shifting down. The more that is generated the more often it appears to the bottom and outside of the container.
Eventually my idea is for all of them to have the same top and left original positions in that way I could use my player and player2 to touch them (match left and top positions) and make them disappear like they are being collected like points. I also cant get them to have the same origin point. I think these issues might be related
You can use to make appeared specific div
z-index: 0
Try adding absolute positioning to your wrapper div and relative positioning to the container div:
#container {
position: relative;
}
#wrapper {
position: absolute;
top: 0;
left: 0;
}
This takes the div out of normal flow from the rest of the document.
See here for more explanations on why this works.

Categories

Resources