【发布时间】:2017-11-29 04:09:15
【问题描述】:
请原谅我对 JS 非常陌生。 我创建了一个非常简单的画布,其中一个矩形由 keydownevents 控制,而一个矩形只是在 rAF 中围绕画布移动。
如果移动的球击中用户矩形以碰撞并反弹回来,但以正确的角度反弹,我现在希望它不会像我尝试过但失败的那样反向击中。
我知道我需要计算它在用户矩形上的位置,但我不知道从哪里开始或如何开始 有人可以指出我正确的方向或给我一个小sn-p该做什么吗?
我将省略 Keycode 函数,因为它们不需要。
function init() {
canvas = document.getElementById("canvasdemo");
ctx = canvas.getContext("2d");
canvasWidth = canvas.width;
canvasHeight = canvas.height;
drawSquare();
}
function drawSquare() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// user controlled square
ctx.fillStyle = "blue";
ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
requestAnimationFrame(drawSquare);
if (rect.x + rect.vx > canvasWidth - 20 || rect.x + rect.vx < 0)
rect.vx = -rect.vx;
if (rect.y + rect.vy > canvasHeight - 20 || rect.y + rect.vy < 0)
rect.vy = -rect.vy;
rect.x += rect.vx;
rect.y += rect.vy;
// Moving Square 1 (left-right):
requestAnimationFrame(squareTwo);
if (dir1 == "right") {
if (xpos < canvasWidth - 35) {
xpos += 2;
}else{
dir1 = "left";
}
}
if (dir1 == "left") {
if (xpos>0) {
xpos -= 2;
}else{
dir1 = "right";
}
}
}
// Second square
function squareTwo() {
ctx.fillStyle = "black";
ctx.fillRect(xpos, ypos, 35, 35);
ctx.fill();
}
【问题讨论】:
-
真正从不动的桨上反弹需要计算球撞击桨的入射角,并让它以相同但反射的角度反弹。如果您想根据桨移动的速度或方向来影响角度,那么这将变得更加复杂,并且将涉及更详细的物理。
-
rect在哪里定义?你的画布的宽度和高度是多少?
-
什么有效,什么无效?你的问题到底是什么?
-
好的 jfriend00 如果桨在进入移动桨之前是静态的,那么基础是什么?我将变量留在 Shashank 以节省空间,一切都被定义为主函数之外的全局变量。 var rect = { x: 250, y: 140, w: 20, h: 20, vx: 0, vy: 0 };画布 w = 550, h = 300
-
桑德我的问题是我如何让一个移动的球以正确的角度从桨上反弹,而填充是 a) 静态和 b) 移动与用户控制
标签: javascript canvas