Simple move javascript game - javascript

what wrong with my code
function move(x,y)
{
setInterval(function()
{
gameArea.clear();
gamePiece.x += x;
gamePiece.y += y;
gamePiece.update();
}, 100);
}
document.getElementsByTagName('body')[0].onkeyup = function(e)
{
var myInterval;
if(e.keyCode == 37)
{
move(10,0);
}
else if(e.keyCode == 38)
{
move(0,-10);
}
else if(e.keyCode == 39)
{
move(-10,0);
}
else if(e.keyCode == 40)
{
move(0,10);
}
}
This produce output i'm not expected, and the object can't move correctly.
Please help me to fixed this.

Related

Am I using keyup correctly?

This is an excerpt from a js file
$searchBox.keyup(function(event) {
if (event.keyCode === 13) { //enter
if(currentResult > -1) {
var result = $searchResults.find('tr.result a')[currentResult];
window.location = $(result).attr('href');
}
} else if(event.keyCode === 38) { //up
if(currentResult > 0) {
currentResult--;
renderCurrent();
}
} else if(event.keyCode === 40) { //down
if(lastResults.length > currentResult + 1){
currentResult++;
renderCurrent();
}
} else {
var query = $searchBox.val();
if (lastQuery !== query) {
currentResult = -1;
if (query.length > 2) {
self.search(query);
} else {
self.hideResults();
}
if(self.hasFilter(getCurrentApp())) {
self.getFilter(getCurrentApp())(query);
}
}
}
});
This means that it should only perform the action if the "Enter", "Up" or "Down" keys are pressed, right? Because the search start happening as soon as any key is pressed.
I also tried changing searchBox.keyup to searchBox.change but that messed up how something else was working.

How do I change a value only when a key is pressed down?

I have tried to make a code where a ball only moves when I press the arrow keys and when I let go it stops, but it continues to move. How can I fix this?
This is the part of the code that I have written:
document.onkeydown = function tast (e) {
if (e.keyCode == 39) { // høyre
høyre = 1;
} else {
høyre = 0;
console.log("ikke høyre")
}
if (e.keyCode == 37) { // venstre
venstre = 1;
} else {
venstre = 0;
}
if (e.keyCode == 38) { // opp
opp = 1;
} else {
opp = 0;
}
if (e.keyCode == 40) { // ned
ned = 1;
} else {
ned = 0;
}
}
if (venstre == 1){
kuler[0].x -= 4;
}
if (høyre == 1){
kuler[0].x += 4;;
}
if (opp == 1){
kuler[0].y -= 4;
}
if (ned == 1){
kuler[0].y += 4;
}
Other then setting your values to 0 on else. Use a onkeyup event handler. Then for onkeypress set your values to 1. And onkeyup set them to 0:
document.onkeydown = function tast (e) {
if (e.keyCode == 39) høyre = 1;
if (e.keyCode == 37) venstre = 1;
if (e.keyCode == 38) opp = 1;
if (e.keyCode == 40) ned = 1;
}
document.onkeyup = function tast2 (e) {
if (e.keyCode == 39) høyre = 0;
if (e.keyCode == 37) venstre = 0;
if (e.keyCode == 38) opp = 0;
if (e.keyCode == 40) ned = 0;
}

Javascript multi animation sheet

I wrote my code using the following javascript library, SimpleGame.js by A. Harris.
My code follows, the problem is that the character does not animate while the arrow keys are pressed, it does animate when same keys are released ... what am I missing? Furthermore, key 39, which should be the left arrow key, does not work at all. Any help appreciated, Thank you.
http://www.retroinvaders.net/multiAnimationTest.html
Multi Animation Test
<script type="text/javascript" src="simpleGame.js"></script>
<script type="text/javascript">
var game;
var background;
var character;
var critter;
window.addEventListener("keydown", keydownHandler, false);
function init() {
game = new Scene();
background = new Sprite(game, "media/rpgMap.png", 800, 600);
background.setSpeed(0, 0);
background.setPosition(400, 300);
character = new Character();
critter = new Critter();
game.start();
}
function update() {
game.clear();
checkCollisions();
background.update();
character.update();
critter.update();
}
function Character() {
tCharacter = new Sprite(game, "media/rpg_sprite_walk.png", 192, 128);
tCharacter.loadAnimation(192, 128, 24, 32);
tCharacter.generateAnimationCycles();
tCharacter.renameCycles(new Array("down", "up", "left", "right"));
tCharacter.setAnimationSpeed(1000);
tCharacter.setPosition(440, 380);
tCharacter.setSpeed(0);
tCharacter.pauseAnimation();
tCharacter.setCurrentCycle("down");
return tCharacter;
}
function keydownHandler(event) {
if (event.keyCode === 37) {
character.playAnimation();
character.setCurrentCycle("left");
character.setMoveAngle(270);
character.changeXBy(-5);
}
if (event.keyCode === 39) {
character.changeXby(5);
character.playAnimation()
character.setMoveAngle(90);
character.setCurrentCycle("right");
}
if (event.keyCode === 38) {
character.playAnimation()
character.changeYby(-5);
character.setMoveAngle(0);
character.setCurrentCycle("up");
}
if (event.keyCode === 40) {
character.changeYby(5);
character.playAnimation()
character.setMoveAngle(180);
character.setCurrentCycle("down");
}
}
function Critter() {
tCritter = new Sprite(game, "media/critter.gif", 30, 30);
tCritter.setSpeed(0);
tCritter.setPosition(200, 200);
return tCritter;
}
function checkCollisions() {
if (character.distanceTo(critter) <= 30) {
critter.hide();
}
}
</script>
You were assigning new animationCycle each time you pressed a key.
It seems that chrome had no time to set the new animation cycles.
Use a flag to change only when needed fix this :
function keydownHandler(event) {
event.preventDefault();
if (event.keyCode === 37) {
if (character.animation.currentCycleName !== "left") {
character.setCurrentCycle("left");
}
character.changeXby(-5);
character.playAnimation();
character.setMoveAngle(270);
}
if (event.keyCode === 39) {
if (character.animation.currentCycleName !== "right") {
character.setCurrentCycle("right");
}
character.changeXby(5);
character.playAnimation()
character.setMoveAngle(90);
}
if (event.keyCode === 38) {
if (character.animation.currentCycleName !== "up") {
character.setCurrentCycle("up");
}
character.changeYby(-5);
character.playAnimation();
character.setMoveAngle(0);
}
if (event.keyCode === 40) {
if (character.animation.currentCycleName !== "down") {
character.setCurrentCycle("down");
}
character.changeYby(5);
character.playAnimation();
character.setMoveAngle(180);
}
}
See fiddle

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/

snake game on jquery/javascript when pressing key, snake moving faster

My JavaScript code is as follows:
$(document).keydown(function(event){
var move, inter;
clearInterval(inter);
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 1500);
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');
};
});​
http://jsfiddle.net/6bKHc/94/
When I hold down one of the arrows keys, the snake is starting to move faster, how can I turn that off? You can test it yourself.
Your setInterval is called inside your eventhandler. Move setinterval outside, along with a shared dir variable. Then you will have no need for clearinterval.
var dir = 'bottom';
setInterval(move = function() {
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 150);
$(document).keydown(function(event){
if(event.which == 40) {
dir = 'top';
} else if(event.which == 39) {
dir = 'left';
} else if(event.which == 37) {
dir = 'right';
} else if(event.which == 38) {
dir = 'bottom';
};
});
​
http://jsfiddle.net/zatsq/

Categories