알고리즘 고민/해결
[해결] 제자리로 오는 방법
커밍이즈스프링
2021. 9. 13. 23:20
반응형
생각보다 너무나 단순했다.
if(y좌표값이 처음 설정한 값이 아닌 경우&&점핑 중인지를 확인 하는 boolean값이 false인 경우) 일 때,
물체의 y값을++ 하고,
jumpTimer를 다시 0으로 대입을 한다.
위와 같은 방법으로 하면, 점프를 한 물체가 다시 제자리로 오게 된다.
하지만, 이렇게 하면 또 다른 문제점이 생긴다.
지면에 착지를 하지 않았음에도 불구하고, 공중에서 이중 점프가 된다.
이제 이 방법만 고안 해 내면 완전 해결이다.
해당 방법은 아래 코드에서 if문에 dino의 y좌표 값이 지면이 아니면 점핑 중인지를 확인 하는 boolean값이 true가 되지 않게 조건문을 하였다.
document.addEventListener("keypress", (e) => {
if (e.code === "Space" && dino.y === 200) {
isJumping = true;
}
});
이처럼 하니 물체가 점프를 하고 다시 제자리로 올 수 있게 되었다.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth - 100;
canvas.height = window.innerHeight - 100;
// 코드를 입력하면 네모(🔲)가 생성이 된다.
const dino = {
x: 10,
y: 200,
width: 50,
height: 50,
draw() {
ctx.fillStyle = "green";
ctx.fillRect(this.x, this.y, this.width, this.height);
},
};
class Cactus {
constructor() {
this.x = 500;
this.y = 200;
this.width = 50;
this.height = 50;
}
draw() {
ctx.fillStyle = "red";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
let timer = 0;
let cactuss = [];
let isJumping = false;
let jumpTimer = 0;
function frameAction() {
requestAnimationFrame(frameAction);
timer++;
const cactus = new Cactus();
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (timer % 120 === 0) {
cactuss.push(cactus);
cactus.draw();
}
cactuss.forEach((a, i, o) => {
a.x--;
if (a.x < 0) {
o.splice(i, 1);
}
a.draw();
});
if (isJumping === true) {
dino.y--;
jumpTimer++;
}
if (jumpTimer > 100) {
isJumping = false;
}
if (isJumping === false && dino.y !== 200) {
dino.y++;
jumpTimer = 0;
}
dino.draw();
}
frameAction();
document.addEventListener("keypress", (e) => {
if (e.code === "Space" && dino.y === 200) {
isJumping = true;
}
});
반응형