I am sticking to the walls but only on the right - javascript

I am currently debugging a game im making in p5.js and have found that i stick to walls that are on the right of my player but not on my left. i have tried turning up the number of pixels away it checks but it doesn't look good and only will work with 5. here is the code:
move(){
let wallcheckL = get(this.x - 1, this.y);
let wallcheckR = get(this.x + (this.scale + 1), this.y);
let wallcheckLB = get(this.x - 1, this.y + this.scale - 5);
let wallcheckRB = get(this.x + (this.scale + 1), this.y + this.scale - 5);
if(wallcheckL[0] == 0 && wallcheckL[1] == 0 && wallcheckL[2] == 255 ||
this.x == 0 ||
wallcheckLB[0] == 0 && wallcheckLB[1] == 0 && wallcheckLB[2] == 255 ||
wallcheckL[0] == 0 && wallcheckL[1] == 128 && wallcheckL[2] == 0) {
this.wallL = true;
}
else{
this.wallL = false;
}
if(wallcheckR[0] == 0 && wallcheckR[1] == 0 && wallcheckR[2] == 255 ||
this.x == 400 - this.scale ||
wallcheckRB[0] == 0 && wallcheckRB[1] == 0 && wallcheckRB[2] == 255 ||
wallcheckR[0] == 0 && wallcheckR[1] == 128 && wallcheckR[2] == 0) {
this.wallR = true;
}
else{
this.wallR = false;
}
if(this.moveR == true && this.wallR == false){
this.x += this.speed;
}
else if(this.moveL == true && this.wallL == false){
this.x -= this.speed;
}
}
also here is the gravity:
gravity(){
let gc = get(this.x, this.y + 21);
let gc2 = get(this.x + this.scale, this.y + 21);
if(gc[0] == 0 && gc[1] == 0 && gc[2] == 255 && gc[3] == 255 ||
this.y >= 400 - this.scale ||
gc2[0] == 0 && gc2[1] == 0 && gc2[2] == 255 && gc2[3] == 255 ||
gc[0] == 255 && gc[1] == 255 && gc[2] == 0 && gc[3] == 255 ||
gc2[0] == 255 && gc2[1] == 255 && gc2[2] == 0 && gc2[3] == 255){
this.gravSpeed = this.dgrav;
this.isOnGround = true;
return;
}
else{
this.y += this.gravSpeed;
if(this.gravSpeed < this.tv){
this.gravSpeed += this.ac;
}
else{
this.gravSpeed = this.tv;
}
this.isOnGround = false;
}
}

Your main problem is in your gravity method, particularly this block of code:
if(gc[0] == 0 && gc[1] == 0 && gc[2] == 255 && gc[3] == 255 ||
this.y >= 400 - this.scale ||
gc2[0] == 0 && gc2[1] == 0 && gc2[2] == 255 && gc2[3] == 255 ||
gc[0] == 255 && gc[1] == 255 && gc[2] == 0 && gc[3] == 255 ||
gc2[0] == 255 && gc2[1] == 255 && gc2[2] == 0 && gc2[3] == 255){
this.gravSpeed = this.dgrav;
this.isOnGround = true;
return;
}
This evaluates irrespective of whether the player is actually on the ground, which results in the issue where the player is getting stuck on the right-hand block.
A potential way to solve it is with actually using code you already have tucked within that condition:
if (this.y >= height - this.scale) {
this.y = height - this.scale; // ensure the player's height is properly constrained
this.gravSpeed = this.dgrav;
this.isOnGround = true;
}
This prevents the sticking as it doesn't set the player variable isOnGround = true when it's not.
Here's a working example:
class player {
constructor(x, y, scale, grav, ac, speed) {
this.x = x;
this.y = y;
this.dtime = 20;
this.jumpTimer = 20;
this.jumpLimit = 12;
this.jumpedHeight = 0;
this.jumping = false;
this.wallR = false;
this.wallL = false;
this.moveR = false;
this.moveL = false;
this.tv = 10;
this.dgrav = grav;
this.ac = ac;
this.speed = speed;
this.gravSpeed = grav;
this.canGravity = true;
this.isOnGround = false;
this.scale = scale;
}
draw() {
fill("red");
rect(this.x, this.y, this.scale, this.scale);
}
gravity() {
let gc = get(this.x, this.y + 21);
let gc2 = get(this.x + this.scale, this.y + 21);
if (this.y >= height - this.scale) {
this.y = height - this.scale;
this.gravSpeed = this.dgrav;
this.isOnGround = true;
} else {
this.y += this.gravSpeed;
if (this.gravSpeed < this.tv) {
this.gravSpeed += this.ac;
} else {
this.gravSpeed = this.tv;
}
this.isOnGround = false;
}
}
move() {
let wallcheckL = get(this.x - 1, this.y);
let wallcheckR = get(this.x + this.scale + 2, this.y);
let wallcheckLB = get(this.x - 1, this.y + this.scale - 5);
let wallcheckRB = get(this.x + this.scale + 2, this.y + this.scale - 5);
if (
(wallcheckL[0] == 0 && wallcheckL[1] == 0 && wallcheckL[2] == 255) ||
this.x == 0 ||
(wallcheckLB[0] == 0 && wallcheckLB[1] == 0 && wallcheckLB[2] == 255) ||
(wallcheckL[0] == 0 && wallcheckL[1] == 128 && wallcheckL[2] == 0)
) {
this.wallL = true;
} else {
this.wallL = false;
}
if (
(wallcheckR[0] == 0 && wallcheckR[1] == 0 && wallcheckR[2] == 255) ||
this.x >= 400 - this.scale ||
(wallcheckRB[0] == 0 && wallcheckRB[1] == 0 && wallcheckRB[2] == 255) ||
(wallcheckR[0] == 0 && wallcheckR[1] == 128 && wallcheckR[2] == 0)
) {
this.wallR = true;
} else {
this.wallR = false;
}
if (this.moveR == true && this.wallR == false) {
this.x += this.speed;
} else if (this.moveL == true && this.wallL == false) {
this.x -= this.speed;
}
}
jump() {
let uc = get(this.x, this.y - 2);
let ucr = get(this.x + this.scale, this.y - 2);
if (
uc[0] == 255 &&
uc[1] == 255 &&
uc[2] == 0 &&
ucr[0] == 255 &&
ucr[1] == 255 &&
ucr[2] == 0
) {
this.y -= 5;
this.jumpedHeight += 1;
} else {
if (
(this.jumpedHeight < this.jumpLimit &&
this.isOnGround == true &&
uc[0] == 255 &&
uc[1] == 255 &&
uc[2] == 255 &&
ucr[0] == 255 &&
ucr[1] == 255 &&
ucr[2] == 255) ||
(this.jumpedHeight < this.jumpLimit &&
this.isOnGround == true &&
uc[0] == 255 &&
uc[1] == 255 &&
uc[2] == 0 &&
ucr[0] == 255 &&
ucr[1] == 255 &&
ucr[2] == 0) ||
(this.jumpedHeight < this.jumpLimit &&
this.isOnGround == true &&
uc[0] == 255 &&
uc[1] == 255 &&
uc[2] == 0 &&
ucr[0] == 255 &&
ucr[1] == 255 &&
ucr[2] == 255)
) {
this.y -= 5;
this.jumpedHeight += 1;
} else {
this.gravSpeed = this.dgrav;
this.jumping = false;
}
}
}
}
class ground{
constructor(x, y, color){
this.x = x;
this.color = color;
this.y = y;
}
draw(){
fill(this.color);
rect(this.x, this.y, 40, 40);
}
}
var groundArray = [];
groundArray[0] = [0];
groundArray[1] = [0];
groundArray[2] = [0];
groundArray[3] = [0];
groundArray[4] = [0];
groundArray[5] = [0];
groundArray[6] = [1,0,0,0,0,0,0,1];
groundArray[7] = [1,0,0,0,0,0,0,1];
groundArray[8] = [1,0,0,0,0,0,0,1];
groundArray[9] = [1,0,0,0,0,0,0,1];
function setup() {
noStroke();
createCanvas(400, 400);
for(let y = 0; y < groundArray.length; y++){
for(let x = 0; x < groundArray[y].length; x++){
if(groundArray[y][x] == 1){
groundArray[y][x] = new ground(x * 40, y * 40, "blue");
}
else if(groundArray[y][x] == 2){
groundArray[y][x] = new ground(x * 40, y * 40, "yellow");
}
else if(groundArray[y][x] == 3){
groundArray[y][x] = new ground(x * 40, y * 40, "green");
}
}
}
}
var play = new player(200, 0, 20, 3, 0.06, 4);
function draw() {
background(255);
for(let y = 0; y < groundArray.length; y++){
for(let x = 0; x < groundArray[y].length; x++){
if(groundArray[y][x] != 0){
groundArray[y][x].draw();
}
}
}
play.move();
if(play.jumping == true){
play.jump();
}
else{
play.gravity();
}
play.draw();
}
function keyPressed(){
if(keyCode == RIGHT_ARROW){
play.moveL = false;
play.moveR = true;
}
else if(keyCode == LEFT_ARROW){
play.moveR = false;
play.moveL = true;
}
if(keyCode == UP_ARROW){
play.jumping = true;
}
}
function keyReleased(){
if(keyCode == RIGHT_ARROW){
play.moveR = false;
}
if(keyCode == LEFT_ARROW){
play.moveL = false;
}
if(keyCode == UP_ARROW){
play.jumping = false;
play.gravSpeed = play.dgrav;
play.jumpedHeight = 0;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>

I have fixed my problem. i found that in my gravity script it was checking too far to the right where it would collide with the wall so i changed it to this and it now works
gravity(){
let gc = get(this.x, this.y + 21);
let gc2 = get(this.x + this.scale - 2, this.y + 21);
if(gc[0] == 0 && gc[1] == 0 && gc[2] == 255 && gc[3] == 255 ||
this.y >= 400 - this.scale ||
gc2[0] == 0 && gc2[1] == 0 && gc2[2] == 255 && gc2[3] == 255 ||
gc[0] == 255 && gc[1] == 255 && gc[2] == 0 && gc[3] == 255 ||
gc2[0] == 255 && gc2[1] == 255 && gc2[2] == 0 && gc2[3] == 255){
this.gravSpeed = this.dgrav;
this.isOnGround = true;
return;
}
else{
this.y += this.gravSpeed;
if(this.gravSpeed < this.tv){
this.gravSpeed += this.ac;
}
else{
this.gravSpeed = this.tv;
}
this.isOnGround = false;
}
}

Related

Check if the "cell" of the "snake" is moving up/down or left/right so I can put the right icon?

How do I check if the "cell" of the "snake" is moving up/down or left/right so I can put the right icon? I have tried everything I know but its still not working.
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style>
html {
background-color: #beb5b5;
}
canvas{
display: block;
margin: 0 auto;
margin-top: 10%;
}
</style>
</head>
<canvas id="snake" width="600" height="600"></canvas>
<script>
const cvs = document.getElementById("snake");
const ctx = cvs.getContext("2d");
// Varje ruta i bilden är 32 px
const box = 30;
// Bilderna
const aplleImg = new Image();
aplleImg.src = "img/apple.png";
const snakeImg = new Image();
snakeImg.src = "img/snakeFront.png";
const snakeTailImg = new Image();
snakeTailImg.src = "img/snakeTailImg.png";
// Låtarna
let dead = new Audio();
let eat = new Audio();
let up = new Audio();
let right = new Audio();
let left = new Audio();
let down = new Audio();
dead.src = "audio/dead.mp3";
eat.src = "audio/eat.mp3";
up.src = "audio/up.mp3";
right.src = "audio/right.mp3";
left.src = "audio/left.mp3";
down.src = "audio/down.mp3";
// Deklarera snake som en array
let snake = [];
snake[0] = { // Bestämmer "huvudets" koordinater
x : 9 * box,
y : 10 * box
};
// Deklarera apple som ett objekt
let apple = {
x : Math.floor(Math.random() * 20 + 1) * box,
y : Math.floor(Math.random() * 16 + 3) * box
}
// Räknar hur många äpplen man har ätit
let score = 0;
//För att kunna kontrollera hur "snake" kommer att röra sig
let d;
document.addEventListener("keydown", direction);
// Här ritas allt i canvas
function draw(){
let x, y;
for (var row = 0; row < 600/30; row++) {
for (var col = 0; col < 600/30; col++) {
x = row * 30;
y = col * 30;
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 600, 90);
if ((row % 2 == 0) == (col % 2 == 0)) {
ctx.fillStyle = "#1cd037";
} else {
ctx.fillStyle = "#387441";
}
ctx.fillRect(x, y, 30, 30);
}
}
for( let i = 0; i < snake.length; i++) { // För att rita alla "celler"
if(i == 0) {
ctx.drawImage(snakeImg, snake[i].x, snake[i].y);
} else {
ctx.drawImage(snakeTailImg, snake[i].x, snake[i].y);
}
}
ctx.drawImage(aplleImg, apple.x, apple.y);
// Allra första koordianten till första cellen/"huvudet"
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// Var ?
if( d == "LEFT") {
snakeX -= box;
snakeImg.src = "img/snakeLeft.png";
}
if( d == "UP") {
snakeY -= box;
snakeImg.src = "img/snakeUp.png";
}
if( d == "RIGHT") {
snakeX += box;
snakeImg.src = "img/snakeRight.png";
}
if( d == "DOWN") {
snakeY += box;
snakeImg.src = "img/snakeDown.png";
}
// När "snake" äter äpplet
if(snakeX == apple.x && snakeY == apple.y){
score++;
eat.play();
apple = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
}else{
snake.pop();
}
// Nytt "huvud"
let newHead = {
x : snakeX,
y : snakeY
}
// Game Over
if(snakeX < 0 || snakeX > 19 * box || snakeY < 3 * box || snakeY > 19 * box || collision(newHead, snake)){
clearInterval(game);
dead.play();
localStorage.setItem("score", score);
setTimeout(function() {location.href="slut.html";}, 600);
}
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "45px Changa one";
ctx.fillText(score, 2 * box, 1.6 * box);
ctx.drawImage(aplleImg, 0.8 * box, 0.5 * box);
ctx.font = "50px Changa one";
ctx.fillText("Snake", 8 * box, 2 * box);
ctx.font = "15px Changa one";
ctx.fillText("Made by: Mohamad Shafeah", 14 * box, 2.8 * box);
}
// Beroende på knappen rör "snake" sig i olika håll
function direction (event) {
let key = event.keyCode;
if( key == 37 || key == 65 && d != "RIGHT"){ // Vänster och "A"
left.play();
d = "LEFT";
}else if(key == 38 || key == 87 && d != "DOWN"){ // Uppe och "W"
d = "UP";
up.play();
}else if(key == 39 || key == 68 && d != "LEFT"){ // Höger och "D"
d = "RIGHT";
right.play();
}else if(key == 40 || key == 83 && d != "UP"){ //Nere och "S"
d = "DOWN";
down.play();
}
}
// Kollar ifall det blir en kollision
function collision (head, array) {
for(let i = 0; i < array.length; i++){
if(head.x == array[i].x && head.y == array[i].y) { // Ifall det blir så måste huvudet vara på samma koordinater som "cellen"
return true;
}
}
return false;
}
// Anropa funktionen draw every 100 ms
let game = setInterval(draw, 100);
</script>
</html>
Two issues that I found were:
In "function direction" you boolean logic is not correct. You have key == 37 || key == 65 && d != "RIGHT" for example. This says if key IS 37 OR key IS 65 AND d IS NOT RIGHT then do X. It should be (key == 37 || key == 65) && d != "RIGHT" for example. This will do a key is X or Key is Y AND check if d is not some value.
I suppect there could also be a scope issue with d. With out access to the assets to make this code runnable it's hard to tell. However, you should really have some sort of object to manage you variable. For example const world = {} then latter on add d to it like world.d = 'SomeValue'. That will fix the scope issue I belive is happening in setInterval(draw, 100)
I would also really change the name of you're lose html to something else in setTimeout(function() {location.href="slut.html";}, 600) Perhapse lose.html
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style>
html {
background-color: #beb5b5;
}
canvas{
display: block;
margin: 0 auto;
margin-top: 10%;
}
</style>
</head>
<canvas id="snake" width="600" height="600"></canvas>
<script>
const world = {}
const cvs = document.getElementById("snake");
const ctx = cvs.getContext("2d");
// Varje ruta i bilden är 32 px
const box = 30;
// Bilderna
const aplleImg = new Image();
aplleImg.src = "img/apple.png";
const snakeImg = new Image();
snakeImg.src = "img/snakeFront.png";
const snakeTailImg = new Image();
snakeTailImg.src = "img/snakeTailImg.png";
// Låtarna
let dead = new Audio();
let eat = new Audio();
let up = new Audio();
let right = new Audio();
let left = new Audio();
let down = new Audio();
dead.src = "audio/dead.mp3";
eat.src = "audio/eat.mp3";
up.src = "audio/up.mp3";
right.src = "audio/right.mp3";
left.src = "audio/left.mp3";
down.src = "audio/down.mp3";
// Deklarera snake som en array
let snake = [];
snake[0] = { // Bestämmer "huvudets" koordinater
x : 9 * box,
y : 10 * box
};
// Deklarera apple som ett objekt
let apple = {
x : Math.floor(Math.random() * 20 + 1) * box,
y : Math.floor(Math.random() * 16 + 3) * box
}
// Räknar hur många äpplen man har ätit
let score = 0;
//För att kunna kontrollera hur "snake" kommer att röra sig
world.d = null;
document.addEventListener("keydown", direction);
// Här ritas allt i canvas
function draw(){
let x, y;
for (var row = 0; row < 600/30; row++) {
for (var col = 0; col < 600/30; col++) {
x = row * 30;
y = col * 30;
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 600, 90);
if ((row % 2 == 0) == (col % 2 == 0)) {
ctx.fillStyle = "#1cd037";
} else {
ctx.fillStyle = "#387441";
}
ctx.fillRect(x, y, 30, 30);
}
}
for( let i = 0; i < snake.length; i++) { // För att rita alla "celler"
if(i == 0) {
ctx.drawImage(snakeImg, snake[i].x, snake[i].y);
} else {
ctx.drawImage(snakeTailImg, snake[i].x, snake[i].y);
}
}
ctx.drawImage(aplleImg, apple.x, apple.y);
// Allra första koordianten till första cellen/"huvudet"
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// Var ?
if( world.d == "LEFT") {
snakeX -= box;
console.log('snakeImg.src = "img/snakeLeft.png";')
snakeImg.src = "img/snakeLeft.png";
}
if( world.d == "UP") {
snakeY -= box;
console.log('snakeImg.src = "img/snakeUp.png";')
snakeImg.src = "img/snakeUp.png";
}
if( world.d == "RIGHT") {
snakeX += box;
console.log('snakeImg.src = "img/snakeRight.png";')
snakeImg.src = "img/snakeRight.png";
}
if( world.d == "DOWN") {
snakeY += box;
console.log('snakeImg.src = "img/snakeDown.png";')
snakeImg.src = "img/snakeDown.png";
}
// När "snake" äter äpplet
if(snakeX == apple.x && snakeY == apple.y){
score++;
eat.play();
apple = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
}else{
snake.pop();
}
// Nytt "huvud"
let newHead = {
x : snakeX,
y : snakeY
}
// Game Over
if(snakeX < 0 || snakeX > 19 * box || snakeY < 3 * box || snakeY > 19 * box || collision(newHead, snake)){
clearInterval(game);
dead.play();
localStorage.setItem("score", score);
setTimeout(function() {location.href="slut.html";}, 600);
}
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "45px Changa one";
ctx.fillText(score, 2 * box, 1.6 * box);
ctx.drawImage(aplleImg, 0.8 * box, 0.5 * box);
ctx.font = "50px Changa one";
ctx.fillText("Snake", 8 * box, 2 * box);
ctx.font = "15px Changa one";
ctx.fillText("Made by: Mohamad Shafeah", 14 * box, 2.8 * box);
}
// Beroende på knappen rör "snake" sig i olika håll
function direction (event) {
let key = event.keyCode;
if( (key == 37 || key == 65) && world.d != "RIGHT"){ // Vänster och "A"
left.play();
world.d = "LEFT";
}else if( (key == 38 || key == 87) && world.d != "DOWN"){ // Uppe och "W"
world.d = "UP";
up.play();
}else if( (key == 39 || key == 68) && world.d != "LEFT"){ // Höger och "D"
world.d = "RIGHT";
right.play();
}else if( (key == 40 || key == 83) && world.d != "UP"){ //Nere och "S"
world.d = "DOWN";
down.play();
}
}
// Kollar ifall det blir en kollision
function collision (head, array) {
for(let i = 0; i < array.length; i++){
if(head.x == array[i].x && head.y == array[i].y) { // Ifall det blir så måste huvudet vara på samma koordinater som "cellen"
return true;
}
}
return false;
}
// Anropa funktionen draw every 100 ms
let game = setInterval(draw, 100);
</script>
</html>

how to get multiple keyboard inputs in javaScript

I am trying to make a pong like game in html, but every time one player try to move the other movement will stop.
//javaScript
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115)
{
p1axis += 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 119)
{
p1axis -= 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 108)
{
p2axis += 2;
document.getElementById("p2").style.top = p2axis + "%";
}
if(x == 111)
{
p2axis -= 2;
document.getElementById("p2").style.top = p2axis + "%";
}
}
I expect that both players will be able to play freely.
instead only one can move at once.
You can create an array and add keys as they are pressed. You will have to remove them as the key is released. Also, I just used keydown with jQuery, you can also use keydown with JavaScript.
var bKeys = [];
$('body').keydown(function(e) {
if (bKeys.includes(e.which) === false) {
bKeys.push(e.which);
}
});
$('body').keyup(function(e) {
bKeys.pop(e.which);
});
setInterval(() => {
console.log(bKeys);
}, 15);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remember to click in the body when you run the code
var k1 = false, k2 = false, k3 = false, k4 = false;
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = true;
}
if(x == 119 || x == 87)
{
k2 = true;
}
if(x == 108 || x == 76)
{
k3 = true;
}
if(x == 111 || x == 79)
{
k4 = true;
}
}
function remove(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = false;
}
if(x == 119 || x == 87)
{
k2 = false;
}
if(x == 108 || x == 76)
{
k3 = false;
}
if(x == 111 || x == 79)
{
k4 = false;
}
}
function move()
{
if(k1)
{
p1axis += 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k2)
{
p1axis -= 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k3)
{
p2axis += 1;
document.getElementById("p2").style.top = p2axis + "%";
}
if(k4)
{
p2axis -= 1;
document.getElementById("p2").style.top = p2axis + "%";
}
setTimeout(move, 20);
}

Format Number allows three digits decimals instead of two

I have created a format that allows two digits after the decimal, for example 99.99 or 55.55 etc. I would like to make it allow 99.999 instead of two. Not sure where the problem is.
function formatNumber (nStr) {
nStr = String(nStr)
nStr = nStr.replace(/\,/g, '')
nStr = trimNumber(nStr)
if ($.isNumeric(nStr)) {
nStr = String(parseFloat(nStr).toFixed(2))
nStr += ''
x = nStr.split('.')
x1 = x[0]
if (x.length > 1) {
if (x[1].length > 2) {
var thirddigit = x[1].substr(2, 1)
var addone = false
if (Number(thirddigit) >= 5) {
addone = true
}
x[1] = x[1].substr(0, 2)
if (addone) {
var y = Number(x[1]) + 1
x[1] = y
}
}
}
x2 = x.length > 1 ? '.' + x[1] : ''
var rgx = /(\d+)(\d{3})/
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2')
}
if (x.length > 1) {
if (x[1].length == 1) {
x2 = '.' + x[1] + '0'
}
if (x[1].length == 0) {
x2 = '.00'
}
} else {
if (x1 != '') {
x2 = '.00'
}
}
if (getLeft(x1 + x2, 1) == '.') {
return '0' + x1 + x2
} else {
return x1 + x2
}
} else {
return ''
}
}
I found the solution! I posted it in case anyone would have the same scenario and needs it.
function Format3DigitDecimal(e, thisobj, min, max) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode))
var inStr = $(thisobj).val()
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
{
if ((inStr.length >= max.toString().length) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
{
ret = false
}
}
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
{
if ((inStr.length == 3) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
{
ret = false
}
}
return ret
}

player movement diagonally - too fast || NodeJS

If I move the player right, left, up or down I move 5px in that direction.
But if I press down and right for example player is moving 5px right and 5px down which is around 7 pixels from the previous position instead 5px.
I can add next IF statement: if (up and down) then spdX and spdY = (maxSpd - maxSpd√2) / or simple -25% ?.
But I think already my code is bit messy...
Any nice solutions which are fast and looks simple? :)
That is my code:
self.updateSpd = function(){
if(self.pressingRight){
self.spdX = self.maxSpd;
if(self.pressingShift && self.stamina > 0){
self.spdX += self.maxRun;
self.stamina --;
}
}
else if(self.pressingLeft){
self.spdX = -self.maxSpd;
if(self.pressingShift && self.stamina > 0){
self.spdX -= self.maxRun;
self.stamina --;
}
}
else{
self.spdX = 0;
}
if(self.pressingUp){
self.spdY = -self.maxSpd;
if(self.pressingShift && self.stamina > 0){
self.spdY -= self.maxRun;
self.stamina --;
}
}
else if(self.pressingDown){
self.spdY = self.maxSpd;
if(self.pressingShift && self.stamina > 0){
self.spdY += self.maxRun;
self.stamina --;
}
}
else{
self.spdY = 0;
}
}
You could make variables for X and Y direction with values -1, 0, 1:
var dirX = -self.pressingLeft + self.pressingRight;
var dirY = -self.pressingUp + self.pressingDown;
Then adjust when moving diagonally:
if (dirX !== 0 && dirY !== 0) {
dirX *= Math.SQRT1_2;
dirY *= Math.SQRT1_2;
}
Then apply the rest:
var speed = self.maxSpd;
if (self.pressingShift && self.stamina > 0 && (dirX !== 0 || dirY !== 0)) {
speed += self.maxRun;
self.stamina--;
}
self.spdX = speed * dirX;
self.spdY = speed * dirY;
All told:
self.updateSpd = function () {
var dirX = -self.pressingLeft + self.pressingRight;
var dirY = -self.pressingUp + self.pressingDown;
if (dirX !== 0 && dirY !== 0) {
dirX *= Math.SQRT1_2;
dirY *= Math.SQRT1_2;
}
var speed = self.maxSpd;
if (self.pressingShift && self.stamina > 0 && (dirX !== 0 || dirY !== 0)) {
speed += self.maxRun;
self.stamina--;
}
self.spdX = speed * dirX;
self.spdY = speed * dirY;
};
Or maybe:
self.updateSpd = function () {
var dirX = -self.pressingLeft + self.pressingRight;
var dirY = -self.pressingUp + self.pressingDown;
var speed = self.maxSpd;
if (self.pressingShift && self.stamina > 0 && (dirX !== 0 || dirY !== 0)) {
speed += self.maxRun;
self.stamina--;
}
if (dirX !== 0 && dirY !== 0) {
speed *= Math.SQRT1_2;
}
self.spdX = speed * dirX;
self.spdY = speed * dirY;
};
Note that this does behave differently from your original when both left and right are pressed (no movement, rather than moving right) or when both up and down are pressed (no movement, rather than moving up).

javascript array problem

i have written a snake program using javascript..
the problem is that the snake does not grow more than 2 blocks size....
<html>
<head>
<script type="text/javascript">
var matrix, body, dir, key, lastx, lasty, start, applex, appley, eat, hal;
function node(x, y) {
this.x = x;
this.y = y;
}
function draw() {
var str;
for (var i = 0; i < body.length; i++) {
matrix[body[i].x * 50 + body[i].y].bgColor = "black";
}
}
function halt() {
hal = 1 - hal;
if (hal == 0) automove();
}
function check_status() {
if (start == 1 && hal == 0) {
var ch;
if (eat == 1) {
do {
ch = 0;
applex = Math.round(49 * Math.random());
appley = Math.round(49 * Math.random());
for (var i = 0; i < body.length; i++)
if (body[i].x == applex && body[i].x == appley) ch = 1;
} while (ch == 1);
matrix[applex * 50 + appley].bgColor = "blue";
eat = 0;
}
lastx = body[body.length - 1].x;
lasty = body[body.length - 1].y;
for (var i = 1; i < body.length; i++) {
body[i].x = body[i - 1].x;
body[i].y = body[i - 1].y;
}
if (dir == 1)--body[0].x;
else if (dir == -1)++body[0].x;
else if (dir == 2)--body[0].y;
else if (dir == -2)++body[0].y;
if (body[0].x == -1 || body[0].x == 50 || body[0].y == 50 || body[0].y == -1) {
alert("GAME OVER!!");
start = 0;
}
for (var i = 1; i < body.length; i++) {
if (body[0].x == body[i].x && body[0].y == body[i].y) {
alert("GAME OVER!!");
start = 0;
i = 10000;
}
}
if (body[0].x == applex && appley == body[0].y) {
eat = 1;
body[body.length] = new node(lastx, lasty);
}
matrix[lastx * 50 + lasty].bgColor = "white";
draw();
}
}
function automove() {
if (start == 1 && hal == 0) {
if (key != -dir) dir = key;
check_status();
window.setTimeout("automove()", 200);
}
}
function init() {
start = 1;
var x = document.getElementById("mine");
var str = "<table id='tab' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >";
for (var i = 0; i < 50; i++) {
str += "<tr>";
for (var j = 0; j < 50; j++)
str += "<td></td>";
str += "</tr>";
}
str += "</table>";
x.innerHTML = str;
matrix = document.getElementsByTagName("td");
body = new Array();
body[0] = new node(0, 0);
draw();
dir = key = -1;
eat = 1;
v = 0;
hal = 0;
automove();
}
function keypress(e) {
if ((e.keyCode == 38) || ((e.which) && (e.which == 38))) //up
key = 1;
else if ((e.keyCode == 40) || ((e.which) && (e.which == 40))) //down
key = -1;
else if ((e.keyCode == 37) || ((e.which) && (e.which == 37))) //left
key = 2;
else if ((e.keyCode == 39) || ((e.which) && (e.which == 39))) //right
key = -2;
check_status();
}
</script>
</head>
<body onkeydown=keypress(event)>
<br/>
<input type="button" onClick="init()" value="play">
<input type="button" onClick="halt()" value="pause">
<p id="mine"></p>
<br><h5 id="score"></h5>
</body>
</html>
The problem is here:
lastx=body[body.length-1].x;
lasty=body[body.length-1].y;
for(var i=1;i<body.length;i++)
{
body[i].x=body[i-1].x;
body[i].y=body[i-1].y;
}
In that loop, body[1] is assigned to body[0], then body [2] is assigned to body[1] etc. This means that everything from index 1 to the end will be set equal to body[0], then body[0] is altered based on direction - so there are only two positions.
Look into the javascript unshift method.
You could replace that loop with:
body.unshift(body[0]);

Categories

Resources