方块在新创建的函数中保持静态

时间:2017-06-12 16:16:28

标签: javascript

我正在为我的游戏测试制作复制功能。在我新创建的函数内部包含新的狼函数并减去对象的x值然后将其绘制到画布上。唯一的问题是页面保持静态,没有任何动作。我使用MDN来研究创建新功能。任何帮助或反馈将不胜感激!继承我的代码



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

var wolfPop = 2;
var bornWolves = 0;

var wolves = {

};

var funs = {

};

var name;
var fname;

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

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

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

function spawnWolf(){
	name = "w" + bornWolves;
	rand = Math.floor(Math.random() * 100) + 1;
	wolves[name] = Object.create({}, {x: {value: Math.floor(Math.random() * 450) + 1}, y: {value: Math.floor(Math.random() * 450) + 1}, h: {value: 10}, w: {value: 10}});
	setupWolf();
	var f1 = createWolfMove();
	f1();
}

function createWolfMove(){
	console.log("called");
	return new Function('var k = wolves[name]; setInterval(function(){ k.x -= 1; context.fillStyle = "cornflowerblue"; context.fillRect(k.x, k.y, k.w, k.h); context.fill();}, 100);');
}

<body id="body">
<canvas id="canvas" height="500px" width="500px"></canvas>
</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

Youre probably looking for inheritance :

You could create new wolves that inherit from a wolf class:

 //setup canvas   
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var body = document.getElementById("body");
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";


var wolfPop = 2;
var bornWolves = 0;
var wolves = [];

function rand(a,b=1){return Math.floor(Math.random() * a) + b;}

//constructor
function Wolf(name,x,y,w,h){
 //setup 
   this.name=name||" w"+bornWolves;
   this.x=x||rand(450);
   this.y=y||rand(450);
   this.w=w||10;
   this.h=h||10;
  //update globals
  wolves.push(this);
  bornWolves++;
}
Wolf.prototype={
  update:function(){
context.fillStyle = "blue";
context.fillRect(this.x, this.y, this.w, this.h);
   },
   moving:false,
   move:function(){
     this.x+=rand(100,-50);//move between 50 and -50
     this.y+=rand(100,-50);/
   }
};



setInterval(function(){
 //clear
 context.clearRect(0, 0, canvas.width, canvas.height);
 //update all wolves
 wolves.forEach(function(wolf){
   if(wolf.moving) wolf.move();
   wolf.update();
 }
if(wolfPop != bornWolves){
    new Wolf();
}
}, 1);

//add a new wolf
var first=new Wolf(false,false,20,20);// a bit fater
first.moving=true;