How can I change background-position with arrow-keys? - javascript

Hi just started trying to learn a little javascript, now for my first programm I wanted to write code that moves the "background-position" when pressing arrow-keys.
So I hope one of you guys can help me to fix my code.
My (not so fancy) Code:
var x = 0;
var y = 0;
function GetChar (event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
posy(move(keyCode, x, y))
posx(move(keyCode, x, y))
}
function move (key, x, y){
if (key === 38){
return y ++;
} if else (key === 40){
return y --;
} if else (key === 39){
return x ++;
} if else (key === 37){
return x --;
} else{
}
}
function posy(movy) {
return body.style.background-position-y + movy * 100;
}
function posx(movx) {
return body.style.background-position-x + movx * 100;
}

I ended up solving it with jQuery:
$(document).ready(function(){
var posx = 0;
var posy = 0;
$(document).keydown(function(e){
if(e.keyCode==40){
posy--;
console.log('down');
}else if(e.keyCode==38){
posy++;
console.log('up');
}else if(e.keyCode==39){
posx--;
console.log('right');
}else if(e.keyCode==37){
posx++;
console.log('left');
}else{
};
console.log(posy);
console.log(posx);
$('body').css('background-position-y', ''+posy*100+'px');
$('body').css('background-position-x', ''+posx*100+'px');
});
});

Related

keycode movement issue with javascript (PacMan)

<script>
var world = [
[2,2,2,2,2,2,2,2,2,2],
[2,1,1,2,1,1,1,1,1,2],
[2,1,1,2,1,2,2,2,1,2],
[2,1,1,2,1,2,1,2,1,2],
[2,1,1,2,1,2,1,2,1,2],
[2,1,1,2,2,2,1,2,1,2],
[2,1,1,1,1,1,1,2,1,2],
[2,1,1,1,1,1,1,1,1,2],
[2,2,2,2,2,2,2,2,2,2],
];
var pacman = {
x: 29,
y: 29,
};
function displayWorld(){
var output = '';
for(var i = 0; i < world.length; i++){
output += "\n<div class='row'>\n";
for(var j = 0; j<world[i].length; j++){
if(world[i][j] == 2)
output +="\n<div class='brick'></div>";
else if (world[i][j] == 1)
output += "\n<div class='coin'></div>";
if (world[i][j] == 0)
output += "\n<div class='empty'></div>";
}
output += "\n</div>";
}
//console.log(output);
document.getElementById('world').innerHTML = output;
}
function displayPacman(){
document.getElementById('pacman').style.left= pacman.x+"px";
document.getElementById('pacman').style.top= pacman.y+"px";
}
displayWorld();
displayPacman();
document.onkeydown = function(e){
if(e.keyCode== 37){
pacman.x -= 30;
}
else if(e.keyCode== 39){
pacman.x += 30;
}
else if(e.keycode== 38){
pacman.y -= 30;
}
else if(e.keycode== 40){
pacman.y += 30;
}
console.log(e.keyCode);
displayPacman();
}
</script>
</body>
</html>
I am working on a simple Pacman game and I'm having problems getting my Pacman to move up and down. Pacman will move left and right with no problem, which lets me know that my pacman id is working, but my VAR y isn't. It's probably something simple I've missed, but I don't see it. Please help
if (e.keyCode == 37) {
pacman.x -= 30;
} else if (e.keyCode == 39) {
pacman.x += 30;
} else if (e.keyCode == 38) {
pacman.y -= 30;
} else if (e.keyCode == 40){
pacman.y += 30;
}
keyCode is case sensitive
You have used
else if(e.keycode== 40){
instead use keyCode

Cocos2d Animation inside a Sprite Object

In a Cocos2d-x V 3.81 project, I am trying to animate a sprite inside an object which extends Sprite, but it does not seem to do anything. Is it even possible to have an animated sprite inside such a node, or does it have to extend Layer to have animation?
var Player = cc.Sprite.extend ({
ctor: function () {
this._super(res.Player_png);
this.UP = false;
this.DOWN = false;
this.LEFT = false;
this.RIGHT = false;
this.ACTION = false;
this.speed = 5;
cc.spriteFrameCache.addSpriteFrame(res.Player_Left_plist);
var leftFrames = [];
for(var i = 0; i < 4; i++)
{
var str = "Left" + i + ".png";
var frame = cc.spriteFrameCache.getSpriteFrame(str);
leftFrames.push(frame);
}
this.leftAnim = new cc.Animation(leftFrames, 0.3);
this.runLeft = new cc.repeatForever(new cc.Animate(this.leftAnim));
this.state = "nothing";
this.nothing = "nothing";
this.scheduleUpdate();
cc.eventManager.addListener (
cc.EventListener.create ({
event: cc.EventListener.KEYBOARD ,
onKeyPressed: function(key, event)
{
if(key == 87) this.UP = true;
else if(key == 65) this.LEFT = true;
else if(key == 83) this.DOWN = true;
else if(key == 68) this.RIGHT = true;
else if (key == 69 || key == 32) this.ACTION = true;
}.bind(this),
onKeyReleased: function(key, event)
{
if(key == 87) this.UP = false;
else if(key == 65) this.LEFT = false;
else if(key == 83) this.DOWN = false;
else if(key == 68) this.RIGHT = false;
else if (key == 69 || key == 32) this.ACTION = false;
}.bind(this)
}),this);
return true;
},
update:function(dt) {
if(this.UP)
{
this.y += this.speed;
this.runAction(this.runLeft);
}
else if(this.DOWN)
{
this.y -= this.speed;
}
if(this.LEFT)
{
this.x -= this.speed;
this.runAction(this.runLeft);
}
else if(this.RIGHT)
{
this.x += this.speed;
}
}
});
I think the problem is this line:
cc.spriteFrameCache.addSpriteFrame(res.Player_Left_plist);
It should read
cc.spriteFrameCache.addSpriteFrames(res.Player_Left_plist);
where SpriteFrames is plural. The method without an 's' on the end is used to load a single cc.SpriteFrame object into the cache, after you've created that SpriteFrame manually. the method WITH an 's' on the end is the one that takes a URL for a plist to load a whole spritesheet at once.
http://www.cocos2d-x.org/reference/html5-js/V3.8/symbols/cc.spriteFrameCache.html
This code works for you outside the sprite class? For example in a regular sprite?
I think this is wrong but I have not tested it:
this.leftAnim = new cc.Animation(leftFrames, 0.3);
this.runLeft = new cc.repeatForever(new cc.Animate(this.leftAnim));
With your code what I'd do:
var leftAnim = new cc.Animation();
for(var i = 0; i < 4; i++)
{
var str = "Left" + i + ".png";
var frame = cc.spriteFrameCache.getSpriteFrame(str);
leftAnim.addSpriteFrame(frame);
}
leftAnim.setDelayPerUnit(0.08);
this.runAction(cc.animate(leftAnim)); //or this.runAction(cc.animate(leftAnim).repeatForever());
Hope it helps
The pluralization was largely the problem.
For those curious, here is the block of functional code:
You are correct. Thank you very much. For those interested, this is the block of functional code:
cc.spriteFrameCache.addSpriteFrames(res.playerRun_plist);
var i,f;
var frames=[];
for (i=1; i <= 4; i++) {
f=cc.spriteFrameCache.getSpriteFrame("playerRun"+i+".png");
frames.push(f);
}
var playerRunAnim = new cc.Animation(frames, 0.1);
this.playerAction = new cc.RepeatForever(new cc.Animate(playerRunAnim));
this.runAction(this.playerAction);

Random "spawn" of divs

I'm trying to create a "spawn point" for a div. I have made it work and I have a working collision detector for it. There are two things I wanted to ask regarding my code.
How do I get my code to work with more than one player (window.i). - At the moment, after an hour of fiddling, I've only broken my code. This whole area screws up the collision detector, I have more than one player showing at times, but I'm unable to move.
How do I make it so that it detects the contact before it happens - I've tried working with the "tank's" margin and subtracting it's width, so that before it makes contact it calls an event, but it has been unsuccessful and completely stopped the collision function working.
I'm sorry that it's asking a lot, I really do understand that, but the issues come into eachother and rebound off so I thought it was best I put it all into one question rather than 2 separate ones an hour apart.
function animate() {
var tank = document.createElement("div");
tank.id= "tank";
tank.style.marginLeft="0px";
tank.style.marginTop="0px";
tank.style.height="10px";
tank.style.width="10px";
document.body.appendChild(tank);
x = parseInt(tank.style.marginLeft);
y = parseInt(tank.style.marginTop);
document.onkeydown = function () {
e = window.event;
if (e.keyCode == '37') {
if (x > 0) {
if (collisionDetector() == false) {
x = x - 10;
tank.style.marginLeft = x + "px";
} else {
alert();
}
}
} else if (e.keyCode == '39') {
if (x < 790) {
if (collisionDetector() == false) {
x = x + 10;
tank.style.marginLeft = x + "px";
} else {
alert();
}
}
} else if (e.keyCode == '38') {
if (y > 0) {
if (collisionDetector() == false) {
y = y - 10;
tank.style.marginTop = y + "px";
} else {
alert();
}
}
} else if (e.keyCode == '40') {
if (y < 490) {
if (collisionDetector() == false) {
y = y + 10;
tank.style.marginTop = y + "px";
} else {
alert();
}
}
}
}
}
window.lives = 3;
function playerSpawn() {
window.i = 1;
while (i > 0) {
var player = document.createElement("div");
randMarL = Math.ceil(Math.random()*80)*10;
randMarT = Math.ceil(Math.random()*50)*10;
player.id = "player";
player.style.marginLeft= randMarL + "px";
player.style.marginTop= randMarT + "px";
player.style.height="10px";
player.style.width="10px";
document.body.appendChild(player);
i--;
}
}
function collisionDetector() {
x1 = tank.style.marginLeft;
x2 = player.style.marginLeft;
y1 = tank.style.marginTop;
y2 = player.style.marginTop;
if ((x1 == x2 && y1 == y2)) {
return true;
} else {
return false;
}
}

Moving right immediately pushes div far off screen region

When I attempt to move the div (tank) to the right ONLY in the first "movement command", and only in that direction, I come across in issue whereby my div shoots off a few thousand pixels to the right, way off of the screen region. Was hoping someone would assist me to see why this is.
function animate() {
var tank = document.getElementById("tank");
tank.style.marginLeft="360px";
tank.style.marginTop="440px";
window.xpos = tank.style.marginLeft;
window.ypos = tank.style.marginTop;
window.x = xpos.replace("px","");
window.y = ypos.replace("px","");
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '37') {
if (x > 0) {
x = x - 20;
tank.style.marginLeft = x + "px";
}
} else if (e.keyCode == '39') {
if (x < 70) {
x = x + 20;
tank.style.marginLeft = x + "px";
}
} else if (e.keyCode == '38') {
if (y > 0) {
y = y - 20;
tank.style.marginTop = y + "px";
}
} else if (e.keyCode == '40') {
if (y < 440) {
y = y + 20;
tank.style.marginTop = y + "px";
}
}
}
checkKey(e);
}
window.lives = 3;
function destroy() {
if (lives != 0) {
alert("Life Lost!");
lives--;
window.collision == false;
animate();
} else {
alert("Try Again!");
}
}
window.collision = true;
function state() {
if (collision == false) {
window.state = 1;
} else if (collision == true) {
window.state = 0;
}
return state;
}
state();
if (state == 1) {
animate();
} else {
destroy();
}
You think you are doing a math operation but what you really are doing a string concatenation. In Javascript "360"-20 equals 340 because in this case the string is converted to a number and then an arithmetic subtraction is performed with both numeric values, however a different set of rules apply for the plus operator: in this case "360"+20 yields "36020" because the number is converted to a string and then both strings are concatenated.
Do this:
window.x = Number(xpos.replace("px",""));
window.y = Number(ypos.replace("px",""));

Snake script is not passing values to variable

So here is my snake script -
http://jsfiddle.net/6bKHc/24/
I started to create a snake game, but basically move(top), move(bottom) e.c. is not working. Any ideas why? I understand that I can't pass the elements to variable like this, so maybe you could show me how to do that correctly?
Ok cleared syntax and took a look at errors this should get you started
$(document).keydown(function(event){
var move, inter;
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
if(dir == 'top') {
snake.stop().animate({"top": "+=5px"});
}
if(dir == 'bottom') {
snake.stop().animate({"top": "-=5px"});
}
if(dir == 'left') {
snake.stop().animate({"left": "+=5px"});
}
if(dir == 'right') {
snake.stop().animate({"top": "-=5px"});
}
}, 500);
if(event.which == 40) {
$(".snake").data('dir','top');
} else if(event.which == 39) {
$(".snake").data('dir','left');
} else if(event.which == 37) {
$(".snake").data('dir','right');
} else if(event.which == 38) {
$(".snake").data('dir','bottom');
}; });​
fiddle
Couple of obvious additions to make:
boundary checking
smoothness of animation.
To make it work you will have to moodify your code like follows :
$(document).keydown(function() {
var inter;
return function(event) {
var move, prevDirection;
clearInterval(inter);
inter = setInterval(move = function(direction) {
var value, prop;
switch (direction || prevDirection) {
case "top":
prop = "top";
value = -5;
break;
case "bottom":
prop = "top";
value = 5;
break;
case "left":
prop = "left";
value = -5;
break;
case "right":
prop = "left";
value = 5;
break;
}
if (direction) prevDirection = direction;
$(".snake").css(prop, $(".snake").position()[prop] + value);
}, 500);
if (event.which == 40) {
move('bottom');
} else if (event.which == 39) {
move('right');
} else if (event.which == 37) {
move('left');
} else if (event.which == 38) {
move('top')
};
}
}());​
​
http://jsfiddle.net/6bKHc/42/

Categories