【发布时间】:2016-05-12 14:02:21
【问题描述】:
我创建了一个看起来有点像“不可能的游戏”的简单代码。我是 javascript 新手,所以我的问题可能听起来有点奇怪,但我创建了一些 opjects,如下所示。当我使用 ctx.fillstyle 更改颜色时,我的所有对象都会更改此特定颜色。我怎样才能给每个对象不同的颜色?
谢谢 ;)
var PlayerX;
var Blocka;
var Ground
var canvas = document.getElementById("gamefield");
ctx = canvas.getContext("2d");
var Gamespeed = 5;
var Gravity = 0.9;
var Score = 0;
var velocity = 0.01;
var jumping;
PlayerX = new Player();
Blocka = new Block(1);
Ground = new Gameground();
setInterval(Update, 20);
function startGame() {
}
function Player() {
// this staat voor verwijzing naar zichzelf
this.width = 30;
this.height = 50;
this.x = canvas.width / 4;
this.y = canvas.height / 3 * 2;
this.draw = function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function Block(kolb) {
this.width = 20;
this.height = 40;
this.show = true;
//this.x = canvas.width/2;
this.x = canvas.width + 20;
this.y = (canvas.height / 3 * 2) + 10;
this.draw = function() {
this.move();
if (this.show) {
if (kolb == 1) {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
}
this.move = function() {
this.x -= Gamespeed;
this.death();
}
this.death = function() {
if (this.x <= 20) {
this.show = false;
}
}
}
function Gameground() {
// this staat voor verwijzing naar zichzelf
this.width = 800;
this.height = 150;
this.x = 0;
this.y = 450;
this.draw = function() {
ctx.fillStyle = "#00FFBF"
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function Update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
Blocka.draw();
PlayerX.draw();
if (PlayerX.x < Blocka.x + Blocka.width &&
PlayerX.x + PlayerX.width > Blocka.x &&
PlayerX.y < Blocka.y + Blocka.height &&
PlayerX.height + PlayerX.y > Blocka.y) {
// collision detected!
ctx.fillStyle = "#FF0000";
}
Ground.draw();
}
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.keyCode == "32") { //kijkt of de spatiebalk is ingedrukt
var interval1, interval2, velo, tijd;
velo = 0.00001;
tijd = 20;
interval1 = setInterval(plus, tijd);
function plus() {
if (velo < 20) {
velo += 1.5;
} else {
velo -= 1.5;
}
if (PlayerX.y > 480) {
clearInterval(interval1);
interval2 = setInterval(min, tijd);
}
PlayerX.y += velo;
console.log(PlayerX.y);
}
function min() {
if (velo < 20) {
velo += 1.5;
} else {
velo -= 1.5;
}
if (PlayerX.y < 430) {
clearInterval(interval2);
}
PlayerX.y -= velo;
console.log(PlayerX.y);
}
}
}
【问题讨论】:
-
你能创建jsfiddle的例子吗?
-
在调用每个
draw()函数之前,您需要更新ctx.fillStyle。 -
谢谢,我已经修好了!
-
@Nielsvangils - 请发布您为修复它所做的工作作为答案并接受它。这样,未来偶然发现此问题的用户可以分享您的知识。
-
@Nielsvangils 干得好!将其添加为答案,而不是评论:)
标签: javascript html css object colors