Ich entwickle eine Simulation und arbeite an der beweglichen Funktion. In der Update-Funktion habe ich zwei Dinge vor: eine for-Schleife, die durch jede Taste im Objekt wolves
und zwei Funktionen move(x, y, up, down, left, right)
und draw(x, y, w, h, color
geht. Ich habe verwendet, also wenn mehr Wölfe hinzugefügt werden, wird es durch jedes einzeln durchlaufen. Wenn move()
aufgerufen wird, werden die Parameter über den Objektschlüssel zugewiesen. Das Problem ist, dass die Werte undefined (wie im Snippet gezeigt) zurückgegeben werden. Jede Hilfe ist sehrObjektschlüssel zugewiesene Parameter zurück undefined
var wolves = {
wolf0: {
x: 10,
y: 10,
w: 10,
h: 10,
up: false,
down: false,
left: false,
right: false
}
};
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var body = document.getElementsByTagName("body");
var movement = ["up", "down", "left", "right"];
//styles
canvas.style.backgroundColor = "black";
body[0].style.overflow = "hidden";
body[0].style.margin = "0px";
//update
var update = setInterval(function(){
//clear anything left over from the last frame;
context.clearRect(0, 0, canvas.width, canvas.height);
//loop through wolves object and update each key
for(i = 0; i < Object.keys(wolves).length; i++){
var wolf = wolves["wolf" + i];
move(wolf.x, wolf.y, wolf.up, wolf.down, wolf.left, wolf.right);
//then draw to the canvas
draw(wolf.x, wolf.y, wolf.w, wolf.h, "blue");
}
}, 1000);
function draw(x, y, w, h, color){
context.fillStyle = color;
context.fillRect(x, y, w, h);
context.fill();
}
function move(x, y, up, down, left, right){
\t var ran = Math.floor(Math.random() * 4) + 0;
\t up = this.up;
\t down = this.down;
\t left = this.left;
\t right = this.right;
\t x = this.x;
\t y = this.y;
\t up = false;
\t down = false;
\t left = false;
\t right = false;
\t switch(movement[ran]){
\t \t case "up":
\t \t \t up = true;
\t \t \t console.log("going up");
\t \t break;
\t \t case "down":
\t \t \t down = true;
\t \t \t console.log("going down");
\t \t break;
\t \t case "left":
\t \t \t left = true;
\t \t \t console.log("going left");
\t \t break;
\t \t case "right":
\t \t \t right = true;
\t \t \t console.log("going right");
\t \t break;
\t \t default:
\t \t \t console.log("movement hasn't happend, the ran number is: " + ran);
\t \t break;
\t }
\t if(up){
\t \t y--;
\t \t console.log("y--;");
\t }
\t if(down){
\t \t y++;
\t \t console.log("y++;");
\t }
\t if(left){
\t \t x--;
\t \t console.log("x--;");
\t }
\t if(right){
\t \t x++;
\t \t console.log("x++;");
\t }
\t console.log("x " + this.x);
\t console.log("y " + this.y);
}
<body>
<canvas id="canvas" height="768px" width="1366px"/>
</body>
'Wölfe [ "Wolf" + [i]]' sollte nicht die [] in ihm. – epascarello
Ich lege das später dort auf, wenn mehr und mehr Wölfe erscheinen, wird es durch jeden hindurchgehen ... oder gibt es einen besseren Weg, dies zu tun? –
Es sollte '" Wolf "+ i' – epascarello