javascript - js中如何使用requestAnimationFrame做出转场效果?
问题描述
我对画布中的跳跃系统很满意,但看起来我需要一些过渡,所以它不会从顶部弹回并弹回底部。过渡将有助于跳跃时的重力效果。
这是我的代码:
function Game() {
this.start = function() {
generateObstacles();
for (var i = 0; i < Obstacles.length; i++) {
Paint.draw(Obstacles[i].x, Obstacles[i].y, Obstacles[i].width, Obstacles[i].height, Obstacles[i].color);
}
this.gravity();
}
this.stop = function() {
}
this.gravity = function() {
let gravity = 0.098;
let gravitySpeed = 0;
function gravityEffect() {
gravitySpeed += gravity;
Paint.erase(myPiece.x, myPiece.y, myPiece.width, myPiece.height);
myPiece.y += gravitySpeed;
Paint.draw(myPiece.x, myPiece.y, myPiece.width, myPiece.height, myPiece.color);
window.requestAnimationFrame(gravityEffect);
}
window.requestAnimationFrame(gravityEffect);
}
this.start();
}
function Paint() {
this.draw = function(x, y, width, height, color) {
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
this.erase = function(x, y, width, height) {
ctx.beginPath();
ctx.clearRect(x, y, width, height);
ctx.closePath();
}
}
function generateObstacles() {
let x = myGame.width;
let y = myGame.height;
let maxWidth = 400;
let minWidth = 100;
let randomWidth = Random(maxWidth, minWidth);
let maxHeight = 20;
let minHeight = 5;
let randomHeight = Random(maxHeight, minHeight);
Obstacles.push(new Obstacle(x - randomWidth, y - randomHeight, randomWidth, randomHeight, true, 'green'));
}
function Random(max, min) {
return Math.floor(Math.random() * (max - min) + 1 + min);
}
function Piece(x, y, width, height, behavior, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.behavior = behavior;
this.color = color;
Paint.draw(this.x, this.y, this.width, this.height, this.color);
}
function Obstacle(x, y, width, height, collidable, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.collidable = collidable;
this.color = color;
}
当我在 myPiece 及其小数中添加 y 时,擦除功能表现不佳。例如,如果它的值为 0.098,则擦除将不准确,为什么,它仅在我在 y 上添加整数时才准确。
解决方案
推荐阅读
- python - PostgreSQL 和 python 3.7 字符串搜索
- javascript - 我无法上班的愚蠢考试任务
- outlook - Microsoft Graph API /me/people 403 禁止错误
- python - 使用 value_counts 将新列添加到数据框
- smtp - Gmail smtp 无法发送电子邮件 javax.mail.AuthenticationFailedException:
- node.js - 在后续意图中获取与原始意图不匹配的参数值
- javascript - 如何在继续之前确保异步函数返回值
- java - 使用中位数 3 的快速排序中的逻辑错误
- python - 使用 Linux 子系统在 Python (os.subprocess) 中调用外部 bash 命令
- webgl - 获取 webGL2 片段着色器上的当前像素位置