2017-06-10 32 views
0

我正在嘗試創建一個生態遊戲,並且正在研究它的產卵方面。我的一個嘗試包括創建多個獨立對象來控制不同的方塊或「狼羣」,隨着仿真的進行。我使用字符串作爲對象名稱的原因是每個新創建的狼都有自己獨立的值(這有助於保持事物自己移動而不是一致)。當創建對象時,它調用要繪製的函數setupWolf。當對象被打印到控制檯時,它不顯示x,y,w或h值。我的繼承人代碼使用字符串聲明對象名稱在畫布上繪製字符

var canvas = document.getElementById("canvas"); 
 
var context = canvas.getContext("2d"); 
 
var body = document.getElementById("body"); 
 

 
var wolfPop = 2; 
 
var bornWolves = 0; 
 

 
var wolves = { 
 

 
}; 
 

 
function setupWolf(x, y, w, h){ 
 
\t context.fillStyle = "blue"; 
 
\t context.fillRect(this.x, this.y, this.w, this.h); 
 
\t context.fill(); 
 
} 
 

 
body.style.overflow = "hidden"; 
 
body.style.margin = "0px"; 
 
canvas.style.backgroundColor = "black"; 
 

 
setInterval(function(){ 
 
\t if(wolfPop != bornWolves){ 
 
\t \t spawnWolf(); 
 
\t \t bornWolves++; 
 
\t } 
 
}, 1); 
 

 
function spawnWolf(x, y, w, h){ 
 
\t name = "w" + bornWolves; 
 
\t this.x = 10; 
 
\t this.y = 10; 
 
\t this.h = 10; 
 
\t this.w = 10; 
 
\t wolves[name] = Object.create({}, {x: {value: this.x}, y: {value: this.y}, h: {value: this.h}, w: {value: this.w}}); 
 
\t wolves[name] = new setupWolf(name.x, name.y, name.w, name.h); 
 
\t console.log(wolves); 
 
}
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<title>AI spawn test</title> 
 
</head> 
 
<body id="body"> 
 
<canvas id="canvas" width="1366px" height="768px"/> 
 
</body> 
 
</html>

+0

「我有問題」 - 請準確地寫出什麼問題 –

+0

(編輯)我列出了將x,y,w,h值分配給其對象的問題(如在控制檯中打印的我的代碼) –

回答

0

首先,我宣佈我再重新分配對象作爲一個函數,並在調用它給人錯誤的產值到控制檯。繼承人是我應該做的

var canvas = document.getElementById("canvas"); 
 
var context = canvas.getContext("2d"); 
 
var body = document.getElementById("body"); 
 

 
var wolfPop = 2; 
 
var bornWolves = 0; 
 

 
var wolves = { 
 

 
}; 
 

 
var name; 
 

 
function setupWolf(x, y, w, h){ 
 
\t context.fillStyle = "blue"; 
 
\t context.fillRect(wolves[name].x, wolves[name].y, wolves[name].w, wolves[name].h); 
 
\t context.fill(); 
 
\t console.log(wolves[name].x); 
 
} 
 

 
body.style.overflow = "hidden"; 
 
body.style.margin = "0px"; 
 
canvas.style.backgroundColor = "black"; 
 

 
setInterval(function(){ 
 
\t if(wolfPop != bornWolves){ 
 
\t \t spawnWolf(); 
 
\t \t bornWolves++; 
 
\t } 
 
}, 1); 
 

 
function spawnWolf(){ 
 
\t name = "w" + bornWolves; 
 
\t rand = Math.floor(Math.random() * 100) + 1; 
 
\t wolves[name] = Object.create({}, {x: {value: Math.floor(Math.random() * 100) + 1}, y: {value: Math.floor(Math.random() * 100) + 1}, h: {value: 10}, w: {value: 10}}); 
 
\t setupWolf(); 
 
\t console.log(wolves[name]); 
 
}
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<title>AI spawn test</title> 
 
</head> 
 
<body id="body"> 
 
<canvas id="canvas" width="1366px" height="768px"/> 
 
</body> 
 
</html>

現在我需要幫助的是物體的獨立運動。感謝您的幫助