애니메이션 요정과 자바스크립트의 상호작용! -(Digital Ocean Hackathon 블로그: 섹션 2)

만약 네가 아직 내가 이 일련의 문장 중의 문장을 읽지 않았다면, 나는 네가 이 문장을 계속 쓰기 전에 읽어 보라고 강력하게 건의한다. 일은 더욱 의미가 있을 것이다.
그래서 만약 모든 것이 계획대로 진행된다면, 우리는 지금 우리의 링크 요정이 용감하게 화면 중앙을 행진할 것이다.10/10 그래픽은 게임용으로는 부족합니다.다행히도, 우리의 영웅과 상호작용하는 데는 몇 개의 HTML/CSS 조정과 자바스크립트 파일 하나만 필요합니다.
다음은 이 프로젝트에 사용할 새sprite 폼입니다. 프로젝트 디렉터리에 저장하고 코드를 작성하십시오.




HTML/CSS 수정


좋습니다. 원본 HTML 파일을 아주 간단하게 시작합니다.우리의 정신적인 친구가 화면 밖에서 어슬렁거리는 것을 방지하기 위해서 우리는 그에게 약간의 경계를 주었다.
이를 위해 sprite-view-framediv 요소를 다른 div와 함께 포장하면 이 div의 종류는 container이다.이제 HTML의 바디가 이렇습니다.
<body>
  <div class="container">
    <div class="sprite-view-frame">
      <div class="sprite-renderer"></div>
    </div>
  </div>
  <script src="script.js"></script>
</body>
이것은 HTML로 충분합니다. 이제 CSS의 일부를 바꾸려고 합니다.:root에서 몇 개의 새로운 변수를 도입하여 시작합시다.그것들은 --sprite-top,--sprite-left--sprite-sheet-url이다.그것들의 용도에 관해서는 그것들의 이름이 매우 뚜렷한 경품일 것이다.당신의 코드가 아래와 같은지 확인하세요.
:root {
  --sprite-width: 64px;
  --sprite-height: 64px;
  --sprites: 2;
  --animation-length: 0.5s;

  /* these are the values that we will modify via JavaScript to interact with the sprite */
  --sprite-top: 50%;
  --sprite-left: 50%;
  --sprite-sheet-url: url("./link-spritesheet-down.png");
}
다음은 새로운 container 요소를 설계합시다.이것은 고의로 <body>의 전체 너비를 채우지 않으므로 특히 주의하십시오.
.container {
  width: 90%;
  height: 90%;
  position: relative;
  top: 5%;
  left: 5%;
}
이후에 우리는 sprite-renderer에 대해 경미한 수정을 해야 한다.여기에서, 우리는 background-image에 설정한 변수로 하드코딩:root을 대체할 것이다
 background-image: var(--sprite-sheet-url); /* the sprite sheet */
그리고 애니메이션 속성을 새로운 선택기로 이동합니다. 이번에는 sprite-renderer에도 하나의 종류.animating가 있을 때만 활성화됩니다.
/* the sprite will only animate when the 'animating' class has been set */
.sprite-renderer.animating {
  animation: animateSprites var(--animation-length) infinite
    steps(var(--sprites));
}
주의해야 할 마지막 수정은 transition-duration에 단점sprite-view-frame을 추가한 것이다.이것은 매끄러운 정령이 화면 위에서 이동하는 데 도움이 될 것이다.
transition-duration: 0.05s; /* adding a short duration here will smooth out the animation when moving the sprite */

HTML/CSS 수정이 완료되었습니다!

JavaScript와 상호 작용


자, 우리는 또다시 우편물의'고기와 감자'코너에 올랐다!마침내 이 애니메이션을 상호작용하는'게임'으로 바꿀 때가 되었다.
여기에 기본 JavaScript 작업 지식이 있는 경우
프로젝트 디렉터리에 script.js 파일을 만든 후 변수를 설정해야 합니다.CSS에 있는 container 요소에 액세스해야 합니다.우리는 :root 요소를 수정할 수 있는classList이 필요하기 때문에 우리도 그것을 잡을 것이다.
// grab our elements to be modified
const root = document.querySelector(".container");
const spriteRenderer = document.querySelector(".sprite-renderer");
다음은sprite가 sprite-renderer 에 있는 위치를 추적하기 위해 변수를 설정합니다.이를 위해 우리는 세 개의 내장 함수container, parseInt()getComputedStyle()를 사용하여 초기getPropertyValue()--sprite-top CSS 변수의 수치를 얻을 것이다.
// grab the initial values where we placed the sprite in CSS
let spriteTop = parseInt(
  getComputedStyle(document.documentElement).getPropertyValue("--sprite-top")
);
let spriteLeft = parseInt(
  getComputedStyle(document.documentElement).getPropertyValue("--sprite-left")
);
우리가 추적해야 할 마지막 변수는 우리의 친구 링크가 직면한 방향이다.
let spriteDirection = "down"; // set an initial direction for the character to face
링크가 표준wasd이동키에 반응하도록 --sprite-left에 감청기를 추가합니다.
document.addEventListener("keydown", (e) => {}
다음 코드는 keydown의 리셋 함수에 위치할 것이다
키를 눌렀을 때, 우리는 우선 이 키가 우리가 원하는 방향키 중의 하나인지 확인해야 한다.만약 없다면, 우리는 버튼을 소홀히 해서 계산 자원을 절약할 수 있다.
  // the following code will only run if we have pressed one of our directional keys
  if (!["w", "a", "s", "d"].includes(e.key)) return;
만약 누르는 키가 유효하다면, 우리는 스위치 블록으로 이동해서 예상한 방향에 따라 어떤 변수를 변경해야 하는지를 결정합니다.
// set up directional keys for moving the sprite (w, a, s, d)
  switch (e.key) {
    case "w":
      spriteDirection !== "up" && (spriteDirection = "up"); // change direction if not already facing up
      spriteTop >= 0 && (spriteTop -= 1); // move the character up if not at the edge
      break;
    case "s":
      spriteDirection !== "down" && (spriteDirection = "down"); // change direction if not already facing down
      spriteTop <= 100 && (spriteTop += 1); // move the character down if not at the edge
      break;
    case "a":
      spriteDirection !== "left" && (spriteDirection = "left"); // change direction if not already facing left
      spriteLeft >= 0 && (spriteLeft -= 0.5); // move the character left if not at the edge
      break;
    case "d":
      spriteDirection !== "right" && (spriteDirection = "right"); // change direction if not already facing right
      spriteLeft <= 100 && (spriteLeft += 0.5); // move the character right if not at the edge
      break;
    default:
      break;
  }
다음에 CSS에서 어떤 sprite표를 사용해야 하는지 알려 드리겠습니다. (주의하십시오. CSS가 변수를 해석하는 방식 때문에 전체 document 문자열을 설정해야 합니다.)
root.style.setProperty(
    "--sprite-sheet-url",
    `url(./link-spritesheet-${spriteDirection}.png)` // tell the CSS what sprite sheet to use based on direction
  );
우리의 정령이 정확한 방향으로 향하고 있을 때, 우리는 CSS에 정령의 애니메이션을 설정하는 방법을 알게 할 것이다.
spriteRenderer.classList.add("animating"); // tell the CSS that we want to animate the sprite
마지막으로 CSS에서 엘프를 EventListener 문장으로 이동시켜 계산한 새로운 좌표를 알려 드리겠습니다.
// move our sprite to the new coordinates
  root.style.setProperty("--sprite-top", `${spriteTop}%`);
  root.style.setProperty("--sprite-left", `${spriteLeft}%`);
결승선이 바로 눈앞에 있다!하나 더 처리해야 할 JavaScript가 있습니다.이번에는 CSS가 관건을 놓을 때 정령 설정을 멈추는 애니메이션을 알려주면 됩니다.
document.addEventListener("keyup", () => {
  spriteRenderer.classList.remove("animating"); // when the key is released, stop animating the sprite sheet
});

아이고!



만약 모든 것이 계획대로 진행된다면, 당신은 지금 스크린에 연결된 모든 네 방향을 걸어갈 수 있을 것이다.게임성은 어때요!?(내가 말했잖아. 내가 여기서 쓰는'게임'은 가벼워.😂)

결론


이 시리즈의 세 번째이자 마지막 글에서 이 모든 개념으로 만든 디지털 해양 해커 경기를 소개하겠습니다.(스포일러 알림: 90년대에 자란 아이라면 윈도 3.1 이상 버전의 컴퓨터를 사용할 수 있다. 이전에 이 게임을 해 본 적이 있을 가능성이 높다!)

기대해주세요!


면책 성명:
나는 창작을 하지 않았고 이 글에서 묘사한 어떤 화소 예술도 가지지 않았다. 나는 단지 그것을 편집하여 본 프로젝트의 요구에 부합하도록 했다.사용한 사이다는 RetroGameZone 소유입니다.

좋은 웹페이지 즐겨찾기