最近在考虑用 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 . Javascript/MySql
RWD響應式網站設計/網頁設計,網頁切版,後台程式管理
精選專案.網頁設計.RWD響應式網站.企業形象網站 / 建築設計類
網站技術:PHP . Javascript/MySql
RWD響應式網站設計/網頁設計,網頁切版,後台程式管理
精選專案.網頁設計.RWD響應式網站.行動版網站 / 服務類
網站技術:PHP . Javascript/MySql
提供韓國空運及海運的代購運輸服務,並擁有高效可靠的倉儲管理系統,為客戶打造快速便捷的服務。對於需要韓國商品的族群提供國際運輸服務,透過高效率的代購服務流程將商品快速送到客戶手上。
傑立資訊事業有限公司電話:(02)2739-9096 | 傳真:(02)2739-6637 | 客服:[email protected] | 臺北市信義區和平東路3段257號6樓map
© 2019 傑立資訊 All rights reserved.| 網站隱私政策