2017-06-10 30 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>

现在我需要帮助的是物体的独立运动。感谢您的帮助