最近在考虑用 DOM 实现 2D 游戏基本动作,其中需要实现精灵(sprite)的行走,跳跃等动作,因为 Canvas 才刚开始学习,于是便想用 CSS3 来实现这个动作。
首先从 dribbble 上找来某位大师的作品:
作为 2D 游戏,要响应键盘的动作就肯定不能直接使用 Gif 图了,于是在 Photoshop 中打开这张图,提取出所有帧:
扣去背景以后拼接成雪碧图:
然后利用 CSS3 的 keyframes 自定義动画:
$spriteWidth: 140px; // 精灵宽度
@keyframes run {
0% {
background-position: 0 0;
}
100% {
background-position: -($spriteWidth * 12) 0; // 12帧
}
}
#sprite {
width: $spriteWidth;
height: 144px;
background: url("../images/sprite.png") 0 0 no-repeat;
animation: run 0.6s steps(12) infinite;
}
实现效果如下:
https://idiotwu.me/css3-running-animation/
其中用到 animation-timing-function 里的 steps() , steps([, [ start | end ] ]?):第一个参数number为指定的间隔数,即把动画分为n步阶段性展示,第二个参数默认为end,设置最后一步的状态,start为结束时的状 态,end为开始时的状态,若设置与animation-fill-mode的效果冲突,而以animation-fill-mode的设置为动画结束的 状态。
所以 animation-timing-function: steps(12) 就相当于:
@keyframes run {
0% { background-position: 0 0; }
8.33% { background-position: -140px 0; }
16.67% { background-position: -280px 0; }
25% { background-position: -420px 0; }
33.33% { background-position: -560px 0; }
41.67% { background-position: -700px 0; }
50% { background-position: -840px 0; }
58.33% { background-position: -980px 0; }
66.67% { background-position: -1120px 0; }
75% { background-position: -1260px 0; }
83.33% { background-position: -1400px 0; }
91.67% { background-position: -1540px 0; }
100% { background-position: 0 0; }
}
#player { animation-timing-function: step-start; }
至此,就完成了人物奔跑动作的实现。
網頁設計.RWD響應式網站.企業形象網站 / 服務類
網站技術:PHP
響應式(RWD)網頁設計,設計UI/UX使用者體驗,可於各種裝置進行網頁瀏覽(PC、平板、手機)。
網頁設計.RWD響應式網站.活動網站 / 其他類
網站技術:PHP
本活動網站呈現方式主要獎品說明、抽獎流程與花絮,完成任務時都可以回到網站來確認中獎結果。有不清楚的地方也可以點選右上角客服位置喔。
網頁設計.RWD響應式網站.企業形象網站 / 服務類
網站技術:PHP/MySql
RWD響應式網頁設計+程式設計
電話:(02)2739-9096 | 傳真:(02)2739-6637 | 客服:[email protected] | 臺北市信義區和平東路3段257號6樓map
© 2019 傑立資訊 All rights reserved.| 網站隱私政策