2016-11-19 2 views
0

Я делаю базовую платформу в свое свободное время, и сейчас я пытаюсь добавить гравитацию. Игра работает на холсте, и поэтому я использую черные пиксели в качестве твердых объектов. Спраймы, которые я делаю, должны падать, когда они не контактируют с сплошной черной линией. Для этого я использую context.getImageData() и свойства позиции x, y, ширины и высоты объекта моего спрайта. Когда я создаю sprite игрока, я назначаю ему положение x в 10, ay положение 10, ширину 50 и высоту 100: var player = new Sprite (10, 10, 50, 100);. Моя проблема в том, что когда я пытаюсь нарисовать спрайт или использовать его позицию y в context.getImageData() он говорит, что y-позиция Nan. Нижеприведенный код представляет собой упрощенную версию с соответствующими переменными.Javascript - свойство объекта имеет значение NaN, даже когда я явно назначаю его числовое значение

//-----------SETUP-------------// 
 
//----GLOBAL VARIABLES---// 
 
var gravityValue = 1; \t \t //amount of change that gravity makes per move 
 
var fallBoxThickness = 1; \t //thickness of fall-box check 
 

 
var canvas = document.getElementById("canvas"); \t \t //get the canvas object 
 
\t canvas.width = 800; \t \t //set the canvas width 
 
\t canvas.height = 600; \t //set the canvas height 
 
var context = canvas.getContext("2d"); \t \t \t \t \t //get the canvas's context, 2d 
 

 

 
//--------OBJECTS---------// 
 
function Sprite (x,y,width,height) { \t \t //sprite object 
 
\t //components 
 
\t this.x = x; \t \t \t \t //sprite x position 
 
\t this.y = y; \t \t \t \t //sprite y position 
 
\t this.width = width; \t \t //image width 
 
\t this.height = height; \t //image height 
 
\t this.dx = 0; \t \t \t //sprite x movement 
 
\t this.dy = 0; \t \t \t //sprite y movement 
 
\t this.gravityEnabled = true; \t //allows sprite falling, must be manually disabled 
 
\t 
 
\t //methods 
 
\t this.draw = function() { \t //draw method 
 
\t \t //context.drawImage(this.src, this.x, this.y); 
 
      //draws the sprite to the canvas 
 
     //it used to do the above, now it outputs it to the output span 
 
     document.getElementById("output").innerHTML = this.y; 
 
\t }; 
 
\t 
 
\t this.move = function() { \t //move method 
 
\t \t if (this.gravityEnabled === true) { \t //if the sprite can fall 
 
\t \t \t var hit = false; \t \t \t //a hit is not yet detected 
 
\t \t \t var checkSpace = context.getImageData(\t //get pixels to see if the sprite ... 
 
\t \t \t \t this.x, parseInt(this.y + this.height), \t \t //... will hit an object below it's lower edge 
 
\t \t \t \t this.x + this.width, this.y + this.height, + fallBoxThickness); 
 
\t \t \t 
 
\t \t \t var i = 0; \t //set i to 0 
 
\t \t \t while (i < checkSpace.length && hit === false) { \t 
 
\t \t \t \t //while the check hasn't finished and a hit isn't detected 
 
\t \t \t \t if (checkSpace[i] < 5 \t \t // 
 
\t \t \t \t && checkSpace[i+1] < 5 \t //if there is a black pixel 
 
\t \t \t \t && checkSpace[i+2] < 5) { \t // 
 
\t \t \t \t \t hit = true; \t \t //record that there is a hit 
 
\t \t \t \t } 
 
\t \t \t \t i = i + 4; \t //add 4 to i 
 
\t \t \t } 
 
\t \t \t if (hit === false) { \t //if the check didn't hit 
 
\t \t \t \t this.dy += gravityValue; \t //add to the fall of the sprite 
 
\t \t \t } else { 
 
\t \t \t \t this.dy = 0; 
 
\t \t \t } 
 
\t \t } 
 
\t \t this.y += this.dy; 
 
\t }; 
 
} 
 

 
//------------PLAYER CREATION---------// 
 
var player = new Sprite (10, 10, 50, 100); \t //create the player object 
 

 
//--------FUNCTIONS--------// 
 
function drawCanvas() { \t //draw everything on the canvas 
 
\t player.draw(); \t //draw the player 
 
} 
 

 
function moveSprites() { 
 
\t player.move(); 
 
} 
 
//----------MAIN-----------// 
 
function main() { 
 
\t moveSprites(); \t //move the sprites 
 
\t drawCanvas(); \t //draw the screen 
 
} 
 

 
setInterval(main,100); \t //run main 10 times a second, 
 
\t \t \t //start the program
<title>ptf2</title> 
 
<canvas id="canvas" style="border:1px solid black;"></canvas> 
 
there was images here but the javascript never gets far enough to render them because of the y-position error.<br> 
 
Instead I am just outputting the value of the player sprite's y-position to the span below.<br> 
 
:<span id="output">this is to prevent it from occasionally being undefined</span>

Кроме того, я действительно не знаю, почему эта версия работает вместо того, что у меня было раньше, так что теперь я буду включать полную версию:

//-----------SETUP-------------// 
 
//----IMAGES----// 
 
document.getElementById("map").style.display = "none"; \t \t //hide the map image 
 
document.getElementById("sprite").style.display = "none"; \t //hide the sprite image 
 

 
//----GLOBAL VARIABLES---// 
 
var gravityValue = 1; \t \t //amount of change that gravity makes per move 
 
var fallBoxThickness = 1; \t //thickness of fall-box check 
 

 
var canvas = document.getElementById("canvas"); \t \t //get the canvas object 
 
\t canvas.width = 800; \t \t //set the canvas width 
 
\t canvas.height = 600; \t //set the canvas height 
 
var context = canvas.getContext("2d"); \t \t \t \t \t //get the canvas's context, 2d 
 

 

 
//--------OBJECTS---------// 
 
function Sprite (x,y,src,width,height,dx,dy) { \t \t //sprite object 
 
\t //components 
 
\t this.x = x; \t \t \t \t //sprite x position 
 
\t this.y = y; \t \t \t \t //sprite y position 
 
\t this.src = document.getElementById(src); \t //sprite source image 
 
\t this.width = width; \t \t //image width 
 
\t this.height = height; \t //image height 
 
\t this.dx = dx; \t \t \t //sprite x movement 
 
\t this.dy = dy; \t \t \t //sprite y movement 
 
\t this.gravityEnabled = true; \t //allows sprite movement, must be manually disabled 
 
\t 
 
\t //methods 
 
\t this.draw = function() { \t //draw method 
 
\t \t context.drawImage(this.src, this.x, this.y); \t //draws the sprite to the canvas 
 
\t }; 
 
\t 
 
\t this.move = function() { \t //move method 
 
\t \t if (this.gravityEnabled === true) { \t //if the sprite can fall 
 
\t \t \t var hit = false; \t \t \t //a hit is not yet detected 
 
\t \t \t var checkSpace = context.getImageData(\t //get pixels to see if the sprite ... 
 
\t \t \t \t this.x, parseInt(this.y + this.height), \t \t //... will hit an object below it's lower edge 
 
\t \t \t \t this.x + this.width, this.y + this.height, + fallBoxThickness); 
 
\t \t \t 
 
\t \t \t var i = 0; \t //set i to 0 
 
\t \t \t while (i < checkSpace.length && hit === false) { \t 
 
\t \t \t \t //while the check hasn't finished and a hit isn't detected 
 
\t \t \t \t if (checkSpace[i] < 5 \t \t // 
 
\t \t \t \t && checkSpace[i+1] < 5 \t //if there is a black pixel 
 
\t \t \t \t && checkSpace[i+2] < 5) { \t // 
 
\t \t \t \t \t hit = true; \t \t //record that there is a hit 
 
\t \t \t \t } 
 
\t \t \t \t i = i + 4; \t //add 4 to i 
 
\t \t \t } 
 
\t \t \t if (hit === false) { \t //if the check didn't hit 
 
\t \t \t \t this.dy += gravityValue; \t //add to the fall of the sprite 
 
\t \t \t } else { 
 
\t \t \t \t this.dy = 0; 
 
\t \t \t } 
 
\t \t } 
 
\t \t this.y += this.dy; 
 
\t }; 
 
} 
 

 
var player = new Sprite (10, 10, "sprite", 50, 100); \t //create the player object 
 
var map = new Sprite (0, 0, "map", 800, 600); \t \t \t //create the map sprite 
 
\t map.gravityEnabled = false; \t \t \t //prevents the map from falling 
 
//--------FUNCTIONS--------// 
 
function drawCanvas() { \t //draw everything on the canvas 
 
\t map.draw(); \t \t //draw the map 
 
\t player.draw(); \t //draw the player 
 
} 
 

 
function moveSprites() { 
 
\t player.move(); 
 
} 
 
//----------MAIN-----------// 
 
function main() { 
 
\t moveSprites(); \t //move the sprites 
 
\t drawCanvas(); \t //draw the screen 
 
\t alert("run"); 
 
} 
 

 
setInterval(main,100); \t //run main 10 times a second, 
 
\t \t \t //start the program
<title>ptf2</title> 
 
<canvas id="canvas" style="border:1px solid black;"></canvas> 
 
<img id="map" src = "assets/map03.png"> 
 
<img id="sprite"src = "assets/sprite.png"> 
 
<script src = "main.js"></script>

Любое просвещение будет принята с благодарностью за то, почему никто этого не делает k с точно такими же значениями. Спасибо.

ответ

0

У вашего конструктора Sprite есть аргументы 7, но вы его обрабатываете только с аргументами 5. Переменные dx и dy - undefined, поэтому они производят NaN после алгебраических операций.

+0

спасибо. Я буду помнить, что буду давать все аргументы при создании объекта в будущем. – ThirtyOddLinesOfCode

Смежные вопросы