0
我正在处理我的LD条目,而且我有点卡住了,所以时间是关键。将绘制的形状移动到新的步骤
我在香草JS工作,并设有网球/乒乓球风格。有两个按钮,一个在画布的上半部分和一个在下半部分。
我有它的工作,所以点击时,他们移动'球' - 或Y轴上的+。 但是我想要它,所以当点击'球'开始移动到另一边,它开始移动到另一边。可以只是0和canvas.height分别, 但我不知道如何去编码这个。
另外一个特点是我想要的是如果'球'碰撞,你只能点击一边。
CodePen:http://codepen.io/anon/pen/objWKN
var canvas, ctx, mouseX, mouseY, btn1, btn2, ball, ballX, ballY, ballSize, Score;
window.onload = function main() {
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
canvas.width = width = 320;
canvas.height = height = 560;
mouseX = 0;
mouseY = 0;
btn1 = new Button(0, width, 0, height/2);
btn2 = new Button(0, width, height/2, height);
moveX = width/2;
moveY = height/2;
ballSize = 20;
ballX = moveX;
ballY = moveY;
document.body.appendChild(canvas);
init();
}
function init() {
document.addEventListener('click', mouseClicked, false);
update();
}
function update() {
ctx.clearRect(0, 0, 300, 300);
ctx.beginPath();
ctx.fillStyle="red";
ctx.rect(0, height/2, width, height/2);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "black";
ctx.arc(ballX, ballY , ballSize/2, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
}
// button object
// checks if within bounds of 'button'
function Button(xL, xR, yT, yB) {
this.xLeft = xL;
this.xRight = xR;
this.yTop = yT;
this.yBottom = yB;
}
Button.prototype.checkClicked = function() {
if (this.xLeft <= mouseX && mouseX <= this.xRight && this.yTop <= mouseY && mouseY <= this.yBottom) return true;
};
// event functions
// get position of mouse if its clicked on the canvas
function mouseClicked(e) {
mouseX = e.pageX - canvas.offsetLeft;
mouseY = e.pageY - canvas.offsetTop;
//btn1 clicked = move up
for (i = ballY; i > height; i++); {
if (btn1.checkClicked()) {
ballY = ballY - 40;
}
};
//btn2 clicked = move up
for (i = ballY; ballY > height; i++); {
if (btn2.checkClicked()) {
ballY = ballY - 40; //========= what to put here? =========
}
};
};
setInterval(update, 10);
任何帮助是极大的赞赏。
谢谢你的时间。
-Jordan